【问题标题】:unable to get to one value from multiple values json python无法从多个值json python中获取一个值
【发布时间】:2017-04-17 14:59:48
【问题描述】:

从事一个项目,这让我发疯,我在网上搜索并发现很少有答案适用于我的其他与 json 相关的查询,但是对于这个来说,它有点噩梦不断收到 TrackStack 错误

这是我的 json

ServerReturnJson = {
    "personId":"59c16cab-9f28-454e-8c7c-213ac6711dfc",
    "persistedFaceIds":["3aaafe27-9013-40ae-8e2a-5803dad90d04"],
    "name":"ramsey,",
    "userData":null
}

data = responseIdentify.read()
print("The following data return :  " + data)

#Parse json data to print just 

load = json.loads(data)

print(load[0]['name']) 

这就是我的问题是我无法获取值形式名称,尝试下一条语句,然后我收到此错误:

Traceback (most recent call last):
  File "C:\Python-Windows\random_test\cogT2.py", line 110, in <module>
    for b in load[0]['name']:
KeyError: 0

使用这个for循环

for b in load[0]['name']:
   print b[load]

任何支持都将受到欢迎,我确信它的一些简单的东西无法弄清楚。

【问题讨论】:

  • 您显示的数据不是列表,因此不会有0 索引。你没有展示你想要得到的东西,我认为for 循环根本没有理由。
  • print("The following data return : " + data) 的输出是什么?

标签: python json python-2.7


【解决方案1】:

了解如何在 JSON 中引用嵌套的字典和列表是最难的部分。这里有几点需要考虑。

使用您的原始数据

ServerReturnJson = {
    "personId":"59c16cab-9f28-454e-8c7c-213ac6711dfc",
    "persistedFaceIds":["3aaafe27-9013-40ae-8e2a-5803dad90d04"],
    "name":"ramsey,",
    "userData":'null'
}

# No index here, just the dictionary key
print(ServerReturnJson['name'])

通过制作字典列表添加第二人称

ServerReturnJson = [{
    "personId":"59c16cab-9f28-454e-8c7c-213ac6711dfc",
    "persistedFaceIds":["3aaafe27-9013-40ae-8e2a-5803dad90d04"],
    "name":"ramsey",
    "userData": 'null'
},
    {
        "personId": "234123412341234234",
        "persistedFaceIds": ["1241234123423"],
        "name": "miller",
        "userData": 'null'
    }
]

# You can use the index here since you have a list of dictionaries
print(ServerReturnJson[1]['name'])

# You can iterate like this
for item in ServerReturnJson:
    print(item['name'])

【讨论】:

    【解决方案2】:

    感谢您的支持,基本上,Microsoft Face API 将返回没有索引的 json,就像 Chris 在第一个示例中所说的那样

    上面的例子只有在你添加以下内容时才有效 data = responseIdentify.read() # 读取传入的响应表单服务器 ServerReturnJson = json.loads(数据)

    所以完整的答案如下:

    dataJson= {
        "personId":"59c16cab-9f28-454e-8c7c-213ac6711dfc",
        "persistedFaceIds":["3aaafe27-9013-40ae-8e2a-5803dad90d04"],
        "name":"ramsey,",
        "userData":'null'
        }
        # add json load here 
        ServerReturnJson = json.loads(dataJson)
        # No index here, just the dictionary key
        print(ServerReturnJson['name'])
    

    感谢 Chris,Chris 提到的最后一件事“理解如何在 JSON 中引用嵌套的字典和列表是最难的部分”100% 同意

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 1970-01-01
      • 2013-03-02
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      相关资源
      最近更新 更多