Python访问嵌套的JSON数据 [英] Python Accessing Nested JSON Data

查看:118
本文介绍了Python访问嵌套的JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用zippopotam.us获取特定城市的邮政编码.除了尝试访问返回TypeError: expected string or buffer

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 code key which returns 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']

完整的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"
}

感谢您的帮助.

推荐答案

我没有意识到第一个嵌套元素实际上是一个数组.正确访问邮政编码密钥的方法如下:

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:

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

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

这篇关于Python访问嵌套的JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆