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的机会并很少,不过做为一种数据交换的方便格式,仍是值的注意。