Ruby parsing JSON
Ruby Parsing JSON Example:
JSON = ' ["A", "B", "C"] '
puts "Unsafe #{unsafe_json
(JSON). Inspect}"
#输出Unsafe
["A", "B", "C"]
Ruby parses JSON to parse the above JSON string into array. Such a method is not safe, for example:
JSON = ' puts ' Danger'll
Robinson '
puts ' Unsafe #{unsafe_json
(JSON). Inspect} "
And what should we export? Unfortunately, there is nothing to parse, jump out a warning: warning:character class has ' [' without escape security 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
waiter.synchronize
do wait_ cond.wait_while {ret.nil.}
End return ret< C18/>end
@ @parser = Safejson.build_safe_json
# Safely parse the JSON input
def safejson.parse (input)
@ @parser. Call (input)
rescue Securityerror return
nil
end
Containing this module, you can use Ruby to parse JSON:
Peoples=safejson.parse ('
{"Peoples '): [{" Name ":" site120 ","
Email ":" site120@163.com "," Sex ":" Male "},
{ ' Name ': ' site120_2 ', ' email ': ' site1
20@163.com_2 ', ' sex ': ' Male _2 '} '} ' puts peoples[' peoples '][1]['
name '
#输出site120_2
Ruby on Rails
Rails has built-in AJAX support through the RJS, and perhaps not many opportunities to use JSON, but as a convenient format for data interchange or a value note, the following
Use the JSON plugin here, install the command
Use examples:
Require "Open-uri"
require ' JSON '
def index
uri = ' * * * *
response = nil
begin
Open (URI) do | http|
Response = Http.read
end
@json = json::p arse (response)
rescue => Text
# exception handling
Logger.error ("getmaillistserror=" + text)
Flash.now[:error] = ' Get mailing list failed. '
End
Here the JSON parser requires that the JSON-formatted key must be quoted, and an exception is resolved if there are no quotes.