user5922898 user5922898 - 1 year ago 102
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

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


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

Answer Source

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

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

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)

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

require 'jsonpath'
counties ='$..County').on(response.to_json)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download