解析字典中的字典列表,以从每个字典中检索特定键的值

时间:2019-10-15 17:19:43

标签: python json dictionary

我得到一个JSON响应,并使用json.loads()将其转换为python字典。所以字典看起来像这样:

{u'body': u'[{"id":"1","entity":"zone","status":"PROCESSING","url":null,"createdOn":"2019-10-11T05:49:11Z"},{"id":"2","entity":"floor","status":"FAILED","url":null,"createdOn":"2019-10-11T05:49:15Z"},{"id":"3","entityType":"apartment","status":"SUCCESS","url":null,"createdOn":"2019-10-11T05:49:18Z"}]',u'isBase64Encoded': False, u'statusCode': 200}

我将此命名为testStatusList。我想检索"status"内每个字典的"body"键的值。我可以通过提供"body"来检索body = testStatusList['body']。现在,字典看起来像:

[
    {
        "id": "1",
        "entityType": "zone",
        "status": "PROCESSING",
        "url": null,
        "createdOn": "2019-03-07T12:47:10Z"
    },
    {
        "id": "2",
        "entityType": "floor",
        "status": "FAILED",
        "url": null,
        "createdOn": "2019-08-19T16:46:13Z"
    },
    {
        "id": "3",
        "entityType": "apartment",
        "status": "SUCCESS",
        "url": null,
        "createdOn": "2019-08-19T16:46:13Z"
    }
]

我尝试了此解决方案[Parsing a dictionary to retrieve a key in Python 3.6

testStatusList= json.loads(status_response['Payload'].read())
    body = testStatusList['body']
    status =[]
    for b in body:
       for k,v in b.items():
           if k == 'status':
               status.append(v) 

但是我不断得到AttributeError: 'unicode' object has no attribute 'items'。是否有其他方法来获取unicode对象的项目?

因此,我基本上想检索所有状态,即“处理中”,“失败”和“成功”,以便当某个特定“ id”发生故障时,我可以设置“ if”条件来显示适当的消息。我对自己的方法非常不确定,因为我是Python的新手。任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:2)

body仍然是您顶部Blob中的(unicode)字符串。在该字符串上再次使用json.loads

body = """[
    {
        "id": "1",
        "entityType": "zone",
        "status": "PROCESSING",
        "url": null,
        "createdOn": "2019-03-07T12:47:10Z"
    },
    {
        "id": "2",
        "entityType": "floor",
        "status": "FAILED",
        "url": null,
        "createdOn": "2019-08-19T16:46:13Z"
    },
    {
        "id": "3",
        "entityType": "apartment",
        "status": "SUCCESS",
        "url": null,
        "createdOn": "2019-08-19T16:46:13Z"
    }
]"""


import json
body = json.loads(body)
status =[]
for b in body:
   for k,v in b.items():
       if k == 'status':
           status.append(v) 
print(status)

结果:

  

['处理中','失败','成功']