閱讀936 返回首頁    go 阿裏雲 go 技術社區[雲棲]


使用ruby解析json

rails1.1已經加入對json的全麵支持,現在的Array,Hash,String,Object...等等都有一個to_json方法,生成 json字符串。反過來,我們該如何解析json呢?查了下https://www.json.org/上麵ruby語言的鏈接,在rubyforge上找到了一個項目。解析json對ruby來說非常簡單,隻要一行代碼:



例子:

None.gifjson = '["a", "B", "C"]'
 
puts "Unsafe #{unsafe_json(json).inspect}"   #輸出Unsafe ["a", "B", "C"]






把上麵的json字符串解析成Array。這樣的方法並不安全,比如:

None.gifjson = 'puts "Danger Will Robinson"'
  puts "Unsafe #{unsafe_json(json).inspect}" 
None.gif







又該輸出什麼呢?很遺憾,解析不出什麼東西,跳出一個警告:
warning: character class has `[' without escape


安全的方法如下:

None.gifmodule SafeJSON
None.gif  require 
'monitor'
None.gif  def SafeJSON.build_safe_json
None.gif    ret 
= nil
None.gif    waiter 
= ''
None.gif    waiter.extend(MonitorMixin)
None.gif    wait_cond 
= waiter.new_cond
None.gif    
None.gif    Thread.start 
do
None.gif      $SAFE 
= 4
ExpandedBlockStart.gifContractedBlock.gif      ret 
= Proc.new dot.gif{|json|
ExpandedSubBlockStart.gifContractedSubBlock.gif        eval(json.gsub(
/(["'])/s*:/s*(['"0-9tfn/[dot.gif{])/)dot.gif{"#{$1}=>#{$2}"})
ExpandedSubBlockEnd.gif      }

InBlock.gif      waiter.synchronize 
do
InBlock.gif        wait_cond.signal
InBlock.gif      end
InBlock.gif    end
InBlock.gif    waiter.synchronize 
do
ExpandedSubBlockStart.gifContractedSubBlock.gif      wait_cond.wait_while 
dot.gif{ ret.nil? }
InBlock.gif    end
InBlock.gif    
return ret
InBlock.gif  end
InBlock.gif  @@parser 
= SafeJSON.build_safe_json
InBlock.gif  
InBlock.gif  # Safely parse the JSON input
InBlock.gif  def SafeJSON.parse(input)
InBlock.gif    @@parser.call(input)
InBlock.gif  rescue SecurityError
InBlock.gif    
return nil
InBlock.gif  end
InBlock.gifend






包含這個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_2

rails通過RJS內置了對AJAX的支持,也許用到json的機會並不多,不過作為一種數據交換的方便格式,還是值的注意。

文章轉自莊周夢蝶  ,原文發布時間5.17

最後更新:2017-05-17 10:02:09

  上一篇:go  地平線譚洪賀:AI芯片怎麼降功耗?從ISSCC2017說起
  下一篇:go  前沿 | 國際可視化盛會PacificVis2017的十個精彩案例