rails1.1已经加入对json的全面支持,现在的Array,Hash,String,Object...等等都有一个to_json方法,生成json字符串。反过来,我们该如何解析json呢?查了下http://www.json.org/上面ruby语言的链接,在rubyforge上找到了一个项目。解析json对ruby来说非常简单,只要一行代码:def unsafe_json(json) eval(json.gsub(/(["'])s*:s*(['"0-9tfn[{])/){"#{$1}=>#{$2}"})end例子:json = '["a", "B", "C"]'puts "Unsafe #{unsafe_json(json).inspect}" #输出Unsafe ["a", "B", "C"]把上面的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 endend包含这个Module,你就可以这样使用:peoples=SafeJSON.parse('{"peoples":[{"name":"site120","email":"site120@163.com","sex":"男"},{"name":"site120_2","email":"site120@163.com_2","sex":"男_2"}]}')puts peoples["peoples"][1]["name"] #输出site120_2rails通过RJS内置了对AJAX的支持,也许用到json的机会并不多,不过作为一种数据交换的方便格式,还是值的注意。 |