【问题标题】:Python Accessing Nested JSON Data [duplicate]Python访问嵌套的JSON数据[重复]
【发布时间】:2014-06-11 23:12:18
【问题描述】:

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

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"
}

【问题讨论】:

  • 将您的 JSON 放入 the tool in this snippet,选中“仅括号”,然后单击您想要将其代码路径复制到剪贴板的节点。

标签: python json


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

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

    r = requests.get('http://api.zippopotam.us/us/ma/belmont')
    j = r.json()
    
    print j['state']
    print j['places'][1]['post code']
    

    【讨论】:

      【解决方案3】:

      在您的代码中 j 已经是 json 数据并且 j['places'] 是列表而不是字典。

       r = requests.get('http://api.zippopotam.us/us/ma/belmont')
       j = r.json()
      
       print j['state']
       for each in j['places']:
          print each['latitude']
      

      【讨论】:

        【解决方案4】:

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

        https://github.com/mewwts/addict

         import requests
         from addict import Dict
         r = requests.get('http://api.zippopotam.us/us/ma/belmont')
         j = Dict(r.json())
        
         print j.state
         print j.places[1]['post code']  # only work with keys without '-', space, or starting with number 
        

        【讨论】:

          猜你喜欢
          • 2020-10-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-15
          • 2021-10-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多