简单实现Ruby解析Json

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"DangerWillRobinson"'puts"Unsafe#{unsafe_json(json).inspect}"

又该输出什么呢?很遗憾,解析不出什么东西,跳出一个警告:warning: character class has `[‘ without escape安全的方法如下:

    moduleSafeJSON require'monitor' defSafeJSON.build_safe_json ret=nil waiter='' waiter.extend(MonitorMixin) wait_cond=waiter.new_cond Thread.startdo $SAFE=4 ret=Proc.new{|json| eval(json.gsub(/(["'])/s*:/s*(['"0-9tfn/[{])/){"#{$1}=>#{$2}"})} waiter.synchronizedowait_cond.signal end end waiter.synchronizedowait_cond.wait_while{ret.nil?}end returnret end @@parser=SafeJSON.build_safe_json #SafelyparsetheJSONinput defSafeJSON.parse(input) @@parser.call(input) rescueSecurityError returnnil end end

包含这个Module,你就可以这样使用Ruby解析Json:

    peoples=SafeJSON.parse('{"peoples":[{"name":"site120","email":"site120@163.com","sex":"男"},{"name":"site120_2","email":"site120@163.com_2","sex":"男_2"}]}') putspeoples["peoples"][1]["name"]#输出site120_2

rails通过RJS内置了对AJAX的支持,也许用到json的机会并不多,不过作为一种数据交换的方便格式,还是值的注意。

既有美妙的风景,也会有称不上景只有风的地方。

简单实现Ruby解析Json

相关文章:

你感兴趣的文章:

标签云: