自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

簡(jiǎn)單實(shí)現(xiàn)Ruby解析Json

開(kāi)發(fā) 后端
雖然我們?cè)趯?shí)際編程中用到Json的機(jī)會(huì)并不是很多,但是對(duì)于編程人員來(lái)說(shuō),有些東西還是需要了解的。比如Ruby解析Json的相關(guān)技巧。

Ruby語(yǔ)言的通途可謂是非常廣泛,而且都能使用簡(jiǎn)單靈活的方式幫助我們實(shí)現(xiàn)許多功能需求。Ruby解析Json就可以用一種非常簡(jiǎn)單的方法來(lái)實(shí)現(xiàn)。#t#

Ruby解析Json例子:

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

Ruby解析Json把上面的json字符串解析成Array。這樣的方法并不安全,比如:

  1. json = 'puts "Danger 
    Will Robinson"'
     
  2. puts "Unsafe #{unsafe_json
    (json).inspect}"  

又該輸出什么呢?很遺憾,解析不出什么東西,跳出一個(gè)警告:warning: character class has `[' without escape安全的方法如下:

  1. module SafeJSON   
  2. require 'monitor'   
  3. def SafeJSON.build_safe_json   
  4. ret = nil   
  5. waiter = ''   
  6. waiter.extend(MonitorMixin)   
  7. wait_cond = waiter.new_cond   
  8. Thread.start do   
  9. $SAFE = 4   
  10. ret = Proc.new {|json|   
  11. eval(json.gsub(/(["'])/s*:/s*
    (['"0-9tfn/[{])/){"#{$1}=
    >#{$2}"}) }   
  12. waiter.synchronize do wait_cond.signal   
  13. end   
  14. end  
  15. waiter.synchronize do wait_
    cond.wait_while { ret.nil? } end   
  16. return ret   
  17. end   
  18. @@parser = SafeJSON.build_safe_json   
  19. # Safely parse the JSON input   
  20. def SafeJSON.parse(input)   
  21. @@parser.call(input)   
  22. rescue SecurityError   
  23. return nil   
  24. end  
  25. end  

包含這個(gè)Module,你就可以這樣使用Ruby解析Json:

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

rails通過(guò)RJS內(nèi)置了對(duì)AJAX的支持,也許用到j(luò)son的機(jī)會(huì)并不多,不過(guò)作為一種數(shù)據(jù)交換的方便格式,還是值的注意。

責(zé)任編輯:曹凱 來(lái)源: 博客園
相關(guān)推薦

2009-12-14 11:12:55

Ruby運(yùn)行

2009-12-14 18:59:27

Ruby解析器

2009-12-14 13:47:28

Ruby簡(jiǎn)單語(yǔ)法

2009-12-17 16:50:54

Ruby簡(jiǎn)單編寫

2009-12-14 17:14:08

Ruby文件操作

2009-12-15 15:55:43

Ruby模塊

2009-12-18 15:56:05

Ruby特殊語(yǔ)法

2009-12-14 13:27:06

Ruby區(qū)間

2009-12-15 14:46:04

Ruby類常量

2009-09-07 15:27:04

C# MessageB

2009-12-17 17:37:42

Ruby on Rai

2009-12-17 13:57:15

Ruby關(guān)鍵字

2009-09-28 11:05:29

Ruby端口掃描

2009-12-18 17:29:02

Ruby創(chuàng)建XML

2009-12-18 16:00:29

Ruby獲取當(dāng)前類名

2009-07-06 15:55:52

Servlet例子Ruby

2009-12-17 13:37:24

Ruby代碼塊

2009-12-16 13:39:27

Ruby元編程

2009-12-17 10:39:01

Ruby數(shù)學(xué)表達(dá)式

2009-12-15 09:43:50

Ruby case w
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)