djangofan djangofan - 6 months ago 21
Ruby Question

Convert a standard JSON array into a 2d array object

In ruby, how would I parse this JSON into a 2d location array object?

I want to convert it to a simple object like this:

[["Seattle"]["Washington"],["Seaton"]["Illinois"]]


I tried a few things and having trouble with it and there are not very many examples of this that I could find via Google search.

{
"data": [
{
"city": "Seattle",
"state": "Washington",
"zip": "98104",
"country": "US",
"empty": false,
"county": null
},
{
"city": "Seaton",
"state": "Illinois",
"zip": "61476",
"country": "US",
"empty": false,
"county": null
}
]
}


Here is what I tried so far (which doesn't get me quite there):

require 'rubygems'
require 'json'
...
parsed = JSON.parse(string)
parsed["data"].each do |location|
unless location["city"].nil?
location.each do |location_item|
puts location_item.inspect
end
end
end

Answer

I would do something like this:

require 'json'
JSON.parse(string)['data'].map { |hash| [hash['city'], hash['state']] }
#=> [["Seattle", "Washington"],["Seaton","Illinois"]]