Example tutorial for parsing JSON format data in Ruby and Ruby on Rails, railsjson
Ruby parsing JSON
Ruby parsing Json example:
json = '["a", "B", "C"]'
puts "Unsafe # {unsafe_json
(json) .inspect} "
#Output Unsafe
["a", "B", "C"]
Ruby parses Json to parse the above json string into an Array. This method is not safe, such as:
json = 'puts "Danger
Will Robinson "'
puts "Unsafe # {unsafe_json
(json) .inspect} "
What should be output? Unfortunately, nothing can be parsed, and a warning appears: warning: character class has `['without escape The safe method is as follows:
module SafeJSON
require 'monitor'
def SafeJSON.build_safe_json
ret = nil
waiter = ''
waiter.extend (MonitorMixin)
wait_cond = waiter.new_cond
Thread.start do
$ SAFE = 4
ret = Proc.new {| json |
eval (json.gsub (/ (["']) / s *: / s *
(['"0-9tfn / [{]) /) {" # {$ 1} => # {$ 2} "})}
waiter.synchronize do wait_cond.signal
end
end
waiter.synchronize do wait_
cond.wait_while {ret.nil?} end
return ret
end
@@ parser = SafeJSON.build_safe_json
# Safely parse the JSON input
def SafeJSON.parse (input)
@@ parser.call (input)
rescue SecurityError
return nil
end
end
Including this module, you can use Ruby to parse Json like this:
peoples = SafeJSON.parse ('
{"peoples": [{"name": "site120", "
email ":" site120@163.com "," sex ":" Male "},
{"name": "site120_2", "email": "site1
20@163.com_2 "," sex ":" 男 _2 "}]} ')
puts peoples ["peoples"] [1] ["name"]
#Output site120_2
Ruby on Rails
Rails has built-in support for AJAX through RJS. Perhaps there are not many opportunities to use json, but as a convenient format for data exchange, it is still worth paying attention to, below
The Json plugin is used here, the installation command
gem install json_pure
Examples of use:
require "open-uri"
require 'json'
def index
uri = '*****'
response = nil
begin
open (uri) do | http |
response = http.read
end
@json = JSON :: parse (response)
rescue => text
# Exception handling
logger.error ("GetMailListserror =" + text)
flash.now [: error] = 'Failed to obtain mailing list. '
end
end
Here, the json parser requires that the key in json format must be enclosed in quotation marks. If there is no quotation mark, an exception will occur in parsing.
Articles you may be interested in:
A simple tutorial on using Ruby to process JSON
How to convert nested objects into json in Ruby