2014-09-04 88 views
4

我有一個像這樣的JSON數組。使用Ruby過濾JSON數組的值

[ 
{"name":"Idaho","state":{"id":1,"name":"A"}}, 
{"name":"Wyoming","state":{"id":1,"name":"A"}}, 
{"name":"Montana","state":{"id":2,"name":"B"}}, 
{"name":"South Dakota","state":{"id":1,"name":"B"}} 
] 

我該如何使用Ruby來僅顯示A的值?

我不認爲sort_by將是答案,因爲我下面只是按字母順序排列它們。我想完全排除B的所有結果。

.sort_by { |a| [a.state.name] } 

什麼是在.rb文件中執行此操作的最有效方法?


我解決了我自己的問題。這就是我實現我想要的。

.select { |a| a.state.name == "A" } 
+0

'a.state.name'是你如何做到這一點在JavaScript中,但在Ruby中,這是一個'[ '狀態'] [ '名']'。 – tadman 2014-09-04 20:40:47

+0

另外值得一提的是['Enumerable#select'](http://ruby-doc.org/core-2.1.2/Enumerable.html#method-i-select)方法。 – tadman 2014-09-04 20:42:13

+0

或者,'str.scan(/ [AZ] [a-zA-Z \ s] +(?=。+:\「A \」。+?$)/)=> [「Idaho」,「Wyoming」 ]'。 – 2014-09-05 00:44:25

回答

3
require 'json' 

json = <<'JSON_STRING' 
[ 
{"name":"Idaho","state":{"id":1,"name":"A"}}, 
{"name":"Wyoming","state":{"id":1,"name":"A"}}, 
{"name":"Montana","state":{"id":2,"name":"B"}}, 
{"name":"South Dakota","state":{"id":1,"name":"B"}} 
] 
JSON_STRING 

data = JSON.parse json 

data.map(&:values).select { |state, values| values["name"] == ?A } 
#=> [["Idaho", {"id"=>1, "name"=>"A"}], ["Wyoming", {"id"=>1, "name"=>"A"}]] 

data.map(&:values).select { |state, values| values["name"] == ?A }.map(&:first) 
#=> ["Idaho", "Wyoming"] 
2
require 'json' 

arr = JSON.parse <<END_OF_JSON 
[ 
{"name":"Idaho","state":{"id":1,"name":"A"}}, 
{"name":"Wyoming","state":{"id":1,"name":"A"}}, 
{"name":"Montana","state":{"id":2,"name":"B"}}, 
{"name":"South Dakota","state":{"id":1,"name":"B"}} 
] 
END_OF_JSON 

results = [] 

arr.each do |hash| 
    results << hash["name"] if hash["state"]["name"] == "A" 
end 

p results 

--output:-- 
["Idaho", "Wyoming"]