Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access this JSON API data in Ruby?

Tags:

json

ruby

I am writing a short Ruby program that is going to take a zipcode and return the names of cities within 2 miles of that zipcode. I successfully called an API and was able to parse the JSON data, but I'm unsure how to access the 'city' key.

url = API call (not going to replicate here since it requires a key)

uri = URI(url)

response = Net::HTTP.get(uri)
JSON.parse(response)

Here's what my JSON looks like.

{
  "results": [
    {
      "zip": "08225",
      "city": "Northfield",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "0.0"
    },
    {
      "zip": "08221",
      "city": "Linwood",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "1.8"
    }
  ]
}

I've been trying to access 'city' like this:

response['result'][0]['city']

This appears to be incorrect. Also tried

response[0][0]['city'] 

And a couple of other permutations of the same code.

How can I get the value 'Northfield' out of the JSON data?

like image 936
Leia_Organa Avatar asked Apr 09 '26 04:04

Leia_Organa


1 Answers

You're almost there, just use results instead of result on the result of JSON.parse(response) instead of on response:

JSON.parse(response)["results"][0]["city"]
#=> "Northfield"
like image 168
Gerry Avatar answered Apr 11 '26 18:04

Gerry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!