user5922898 user5922898 - 2 months ago 7
Ruby Question

Iterate through json response and return one array

Code below returns me all counties as a string, I can see that by using inspect method.

def self.all_counties
response['ChargeDevice'].each do |charger|
puts ['ChargeDeviceLocation']['Address']['County'].inspect
end
end


What would be the right way to store every returned string in one array so I can manipulate it later?

JSON

"ChargeDeviceLocation" => {
"Latitude" =>"51.605591",
"Longitude" =>"-0.339510",
"Address" => {
"County" =>"Greater London",
"Country" =>"gb"
}

Answer

This works if the response has all the keys for every item:

counties = response['ChargeDevice'].map do |r|
  r.dig('ChargeDeviceLocation', 'Address', 'County')
end

Something like this will give you nils when the tree doesn't have entries for all items:

counties = response['ChargeDevice'].map do |r|
  r.fetch('ChargeDeviceLocation', {}).
    fetch('Address', {}).
    fetch('County', nil)
end

You could also use JSONPath (and ruby JSONPath gem).

require 'jsonpath'
counties = JsonPath.new('$..County').on(response.to_json)