Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter JSON array by value with Ruby

Tags:

json

arrays

ruby

I have a JSON array that looks something like this.

[
 {"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?

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 { |a| [a.state.name] }

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


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

.select { |a| a.state.name == "A" }
like image 201
localhost Avatar asked Sep 04 '14 20:09

localhost


2 Answers

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"]
like image 151
Todd A. Jacobs Avatar answered Oct 21 '22 05:10

Todd A. Jacobs


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"]
like image 22
7stud Avatar answered Oct 21 '22 03:10

7stud