Ruby語言的通途可謂是很是普遍,並且都能使用簡單靈活的方式幫助咱們實現許多功能需求。Ruby解析Json就能夠用一種很是簡單的方法來實現。json
Ruby特殊語法概念解析安全
Ruby獲取當前類名代碼示例解析ide
Ruby模塊OpenURI獲取HTTP/FTP地址內容ui
淺析Ruby加密實現代碼範例編碼
Ruby blocks提供靈活編碼手段加密
Ruby解析Json例子:spa
json = '["a", "B", "C"]'orm
puts "Unsafe #{unsafe_json
(json).inspect}" xml
#輸出Unsafe
["a", "B", "C"] ci
Ruby解析Json把上面的json字符串解析成Array。這樣的方法並不安全,好比:
json = 'puts "Danger
Will Robinson"'
puts "Unsafe #{unsafe_json
(json).inspect}"
又該輸出什麼呢?很遺憾,解析不出什麼東西,跳出一個警告:warning: character class has `[' without escape安全的方法以下:
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
包含這個Module,你就能夠這樣使用Ruby解析Json:
peoples=SafeJSON.parse('
{"peoples":[{"name":"site120","
email":"site120@163.com","sex":"男"},
{"name":"site120_2","email":"site1
20@163.com_2","sex":"男_2"}]}')
puts peoples["peoples"][1]["name"]
#輸出site120_2
rails經過RJS內置了對AJAX的支持,也許用到json的機會並很少,不過做爲一種數據交換的方便格式,仍是值的注意。