Python 访问嵌套的 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23306653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:42:55  来源:igfitidea点击:

Python Accessing Nested JSON Data

pythonjsonrest

提问by apardes

I'm trying to get the zip code for a particular city using zippopotam.us. I have the following code which works, except when I try to access the post codekey which returns TypeError: expected string or buffer

我正在尝试使用 zippopotam.us 获取特定城市的邮政编码。我有以下代码有效,除非我尝试访问post code返回的密钥TypeError: expected string or buffer

r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()

data = json.loads(j)

print j['state']
print data['places']['latitude']

Full JSON output:

完整的 JSON 输出:

{
"country abbreviation": "US",
"places": [
    {
        "place name": "Belmont",
        "longitude": "-71.4594",
        "post code": "02178",
        "latitude": "42.4464"
    },
    {
        "place name": "Belmont",
        "longitude": "-71.2044",
        "post code": "02478",
        "latitude": "42.4128"
    }
],
"country": "United States",
"place name": "Belmont",
"state": "Massachusetts",
"state abbreviation": "MA"
}

Thanks for your help.

谢谢你的帮助。

采纳答案by apardes

I did not realize that the first nested element is actually an array. The correct way access to the post code key is as follows:

我没有意识到第一个嵌套元素实际上是一个数组。获取邮编key的正确方式如下:

r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()

print j['state']
print j['places'][1]['post code']

回答by agrinh

Places is a list and not a dictionary. This line below should therefore not work:

Places 是一个列表而不是字典。因此,下面的这一行应该不起作用:

print data['places']['latitude']

You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:

您需要在场所中选择一项,然后您可以列出场所的属性。因此,要获得您要做的第一个邮政编码:

print data['places'][0]['post code']

回答by MONTYHS

In your code j is Already json data and j['places'] is list not dict.

在您的代码中, j 已经是 json 数据,而 j['places'] 是 list 而不是 dict。

 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = r.json()

 print j['state']
 for each in j['places']:
    print each['latitude']

回答by Ezequiel Bertti

I'm using this lib to access nested dict keys

我正在使用这个库来访问嵌套的字典键

https://github.com/mewwts/addict

https://github.com/mewwts/accident

 import requests
 from addict import Dict
 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 ad = Dict(r.json())

 print j.state
 print j.places[1]['post code']  # only work with keys without '-', space, or starting with number