0

I'm work with json gem in ruby. Im trying to print second level field such as [address/city/born_in].My ruby code is

json = File.read('person.json')
person = JSON.parse(json)
pp person
puts person["address"]["city"]["born_in"]

My json file as follows..,

{ "FirstName":"John", "lastName":"Smith", "age":25, "address":[ { "streetAddress":"21 2nd Street", "state":"NY", "postalCode":"10021" }, { "city":{ "born_in":"New York", "living_in":"Mumbai" } } ] }

It shows the following error..,

parsingjson.rb:15:in `[]': can't convert String into Integer (TypeError)
        from parsingjson.rb:15:in `<main>'

2 Answers2

1

Your address field is an array. You should use indexes to refer to its elements.

puts person["address"][0]["streetaddress"]
puts person["address"][1]["city"]["born_in"]
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
0

the result of person['address'] is Array, you can use this

puts person['address'][1]['city']['born_in']
Richie Min
  • 654
  • 5
  • 15