Python Can';t获取JSON dict密钥
我试图解析上面的json数据,并通过这样做获得“zip”值Python Can';t获取JSON dict密钥,python,json,python-3.x,parsing,dictionary,Python,Json,Python 3.x,Parsing,Dictionary,我试图解析上面的json数据,并通过这样做获得“zip”值 { "response": { "version": "0.1", "termsofService": "http://www.wunderground.com/weather/api/d/terms.html", "features": { "conditions": 1 } }, "current_observation
{
"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",
}
}
}
然后我会得到这个错误
j = json.loads(string)
keys = j.keys()
print(keys)
#current_observation
print(j['current_observation']['zip'])
回溯(最近一次呼叫最后一次):
文件“\wunder.py”,第17行,在
打印(j['current_observation']['zip'])
KeyError:'zip'
因此,我试图总结一下,解析JSON数据并获得zip值,但收效甚微 您错过了由
display\u location
映射的词典:
Traceback (most recent call last):
File ".\wunder.py", line 17, in <module>
print(j['current_observation']['zip'])
KeyError: 'zip'
print(keys)
提供了什么?如果无法确保JSON格式正确,请查看是否可以使用:for key,value in j.items():print key,value
进行迭代。我发现JSON存在两个问题。将json放在问题中是:1-为image
2添加一个右括号-删除zip
后的逗号-您可以接受下面的正确答案。既然Json格式正确,您就可以看到它了。
print(j['current_observation']['display_location']['zip'])