Ruby解析JSON
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? } 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
Ruby on Rails中
rails通過RJS內置了對AJAX的支持,也許用到json的機會并不多,不過作為一種數(shù)據(jù)交換的方便格式,還是值的注意,下面
這里使用到Json插件,安裝命令
gem install json_pure
使用例子:
require "open-uri" require 'json' def index uri = '*****' response = nil begin open(uri) do |http| response = http.read end @json = JSON::parse(response) rescue => text # 異常處理 logger.error("GetMailListserror=" + text) flash.now[:error] = '獲取郵件列表失敗。' end end
這里json解析器需要json格式的key必須帶引號,如果沒有引號的話會解析出現(xiàn)異常。