Printing JSON elements

Francesco Mantovani picture Francesco Mantovani · May 25, 2017 · Viewed 10.1k times · Source

There is something I don't understand about how to print a JSON element. With Yelp, thanks to this query "https://api.yelp.com/v3/businesses/search?cc=FR&location=Toulouse&categories=movietheaters&limit=1" I can retrieve this JSON:

{
  "businesses": [
    {
      "id": "gaumont-wilson-toulouse-2",
      "name": "Gaumont Wilson",
      "image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/dYJc874NnEJ9-jX2amrLvw/o.jpg",
      "is_closed": false,
      "url": "https://www.yelp.com/biz/gaumont-wilson-toulouse-2?adjust_creative=Xi9rQmCT871UpMvNRzAfuw&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=Xi9rQmCT871UpMvNRzAfuw",
      "review_count": 165,
      "categories": [
        {
          "alias": "movietheaters",
          "title": "Cinema"
        }
      ],
      "rating": 4,
      "coordinates": {
        "latitude": 43.6044154,
        "longitude": 1.4475916
      },
      "transactions": [],
      "location": {
        "address1": "3 place du Président Thomas Wilson",
        "address2": null,
        "address3": null,
        "city": "Toulouse",
        "zip_code": "31000",
        "country": "FR",
        "state": "31",
        "display_address": [
          "3 place du Président Thomas Wilson",
          "31000 Toulouse",
          "France"
        ]
      },
      "phone": "+33534445050",
      "display_phone": "+33 5 34 44 50 50",
      "distance": 451.43923036020004
    }
  ],
  "total": 11,
  "region": {
    "center": {
      "latitude": 43.602510035320684,
      "longitude": 1.4426422119140625
    }
  }
}

then I look into JSON this way:

response_data = response.json()
for i in response_data['businesses']:
    print i['name']

but the 'name' is the only thing I can print!

I cannot print 'address1', 'city' or 'zip_code'.

Why?

Answer

UltraInstinct picture UltraInstinct · May 25, 2017

Because those keys do not exist at that hierarchy within the JSON. They exist within the dictionary against the "location" key. You'd want to use:

print i["name"]["location"]["address1"]