0

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"
  }
10
  • 3
    Use map instead of each and store the result in a variable. Commented Oct 3, 2016 at 11:49
  • You may also find it helpful to use Hash#dig instead of repeated [] calls, to avoid nil errors. Commented Oct 3, 2016 at 12:01
  • i.e. charger.dig('ChargeDeviceLocation', 'Address', 'County') Commented Oct 3, 2016 at 12:02
  • My guess is that your example raises a TypeError: no implicit conversion of String into Integer exception, because there is no Address index on the ['ChargeDeviceLocation'] array. Commented Oct 3, 2016 at 12:02
  • Oh, and obviously... returns me all counties as a string -- what string? If an API is returning the data as a string, then you can presumably convert it into array - but I can't tell you how, without knowing what the original string is! Commented Oct 3, 2016 at 12:05

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.