oso9817
oso9817

Reputation: 117

Can't grab JSON dict key

{
    "response": {
        "version": "0.1",
        "termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
        "features": {
            "conditions": 1
        }
    },

    "current_observation": {
        "image": {
            "url": "http://icons.wxug.com/graphics/wu2/logo_130x80.png",
            "title": "Weather Underground",
            "link": "http://www.wunderground.com"
        },
        "display_location": {
            "full": "San Francisco, CA",
            "city": "San Francisco",
            "state": "CA",
            "state_name": "California",
            "country": "US",
            "country_iso3166": "US",
            "zip": "94102",
        }
    }
}

I was trying to parse this json data above and get the 'zip' value by doing this

j = json.loads(string)
keys = j.keys()
print(keys)
#current_observation

print(j['current_observation']['zip'])

then I would get this error

Traceback (most recent call last):
  File ".\wunder.py", line 17, in <module>
    print(j['current_observation']['zip'])
KeyError: 'zip'

So what I'm trying to do to sum it up is parse the JSON data and get the zip value with little success.

Upvotes: 1

Views: 55

Answers (1)

falsetru
falsetru

Reputation: 369444

You missed a dictionary mapped by display_location:

print(j['current_observation']['display_location']['zip'])

Upvotes: 2

Related Questions