Ruby语言的通途可谓是非常广泛,而且都能使用简单灵活的方式帮助我们实现许多功能需求。Ruby解析Json就可以用一种非常简单的方法来实现。
Ruby特殊语法概念解析
Ruby获取当前类名代码示例解析
Ruby模块OpenURI获取HTTP/FTP地址内容
浅析Ruby加密实现代码范例
Ruby blocks提供灵活编码手段
Ruby解析Json例子:
json = '["a", "B", "C"]'
puts "Unsafe #{unsafe_json
(json).inspect}"#输出Unsafe
["a", "B", "C"]
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? } endreturn 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的机会并不多,不过作为一种数据交换的方便格式,还是值的注意。