使用Ruby按值过滤JSON数组

时间:2022-07-03 20:29:46

I have a JSON array that looks something like this.

我有一个看起来像这样的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"}}
]

How would I use Ruby to only show the value of A?

我如何使用Ruby仅显示A的值?

I don't think sort_by will be the answer because what I have below just sorts them alphabetically. I want to completely exclude all results from B.

我不认为sort_by会是答案,因为我在下面的内容只是按字母顺序对它们进行排序。我想完全排除B的所有结果。

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

What would be the most efficient way to do this in a .rb file?

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


I solved my own question. This is how I achieved what I wanted.

我解决了自己的问题。这就是我实现我想要的方式。

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

2 个解决方案

#1


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


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"]

#1


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


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"]