首页 > 解决方案 > Schrodingers JSON - 使用 json 文档时,它同时作为列表和字典出错

问题描述

我有一个来自 API 调用的 Python 列表:

[{'_id': '5f563c1bf8eaa9d98eca231f',
  'allEnabledDs': None,
  'allEnabledIdSor': None,
  'correlationFilterEntitySource': True,
  'correlation_completed': True,
  'correlation_completed_dt': '2020-09-07T13:56:43.547Z',
  'created_at': '2020-09-07T13:56:43.469Z',
  'dsConnectionList': None,
  'folderToLabelMapping': None,
  'idConnectionList': None,
  'identities_scanned': 0,
  'identityResolutionScan': False,
  'info': None,
  'isCustomScanProfile': None,
  'modelId': None,
  'name': 'Identity Discovery Scan',
  'origin': 'Identity Discovery Scan',
  'piisummary_completed_dt': '2020-09-07T13:56:43.642Z',
  'scan_progress_status': {'Started': '2020-09-07T13:56:43.469Z'},
  'shouldCreateClassifiers': None,
  'skipIdScan': None,
  'state': 'Started',
  'stopRequested': True,
  'type': 'identityDiscoveryScan',
  'updated_at': '2020-09-07T16:59:45.294Z'}]

这是我的代码:

    for i in live_scans:
        url = url 
        payload = {}
        headers = {
            "Authorization": token
        }
        r = requests.get(url, headers=headers, data=payload)
        j_doc = r.json()
        d = {k:v for k,v in (x.split(':') for x in j_doc)}
        if j_doc['state'] == "Stopped":
            print("YAY!")
        if d['state'] == "Stopped":
            print("YAY!")

但是,当使用此代码时:

if n_dict['state'] == "Stopped":
        print("YAY!")

发生此错误:

TypeError: list indices must be integers or slices, not str>

并且在尝试将列表拆分为 dict 时:

d = {k:v for k,v in (x.split(':') for x in j_doc)}

有人可以告诉我为什么会发生这种情况以及如何解决它吗?

标签: pythonlistdictionary

解决方案


正如推荐中提到的@Hitobat - 你有一个里面有字典的列表,所以你必须使用它[0]来获取这本字典。for或者,如果列表中有更多元素,则必须使用-loop

data = [{'_id': '5f563c1bf8eaa9d98eca231f', 'allEnabledDs': None, 'allEnabledIdSor': None, 'correlationFilterEntitySource': True, 'created_at': '2020-09-07T13:56:43.469Z', 'dsConnectionList': None, 'folderToLabelMapping': None, 'idConnectionList': None, 'identityResolutionScan': False, 'info': None, 'isCustomScanProfile': None, 'modelId': None, 'name': 'Identity Discovery Scan', 'origin': 'Identity Discovery Scan', 'scan_progress_status': {'Started': '2020-09-07T13:56:43.469Z'}, 'shouldCreateClassifiers': None, 'skipIdScan': None, 'state': 'Started', 'type': 'identityDiscoveryScan', 'updated_at': '2020-09-07T16:59:45.294Z', 'identities_scanned': 0, 'correlation_completed': True, 'correlation_completed_dt': '2020-09-07T13:56:43.547Z', 'piisummary_completed_dt': '2020-09-07T13:56:43.642Z', 'stopRequested': True}]

print( data[0]['state'] )

for item in data:
    print( item['state'] )

下次你可以type()用来检查你有什么——

print( type(data) )

如果是,list那么您可以测试长度和/或检查第一个元素

print( len(data) )
print( type( data[0] ) )

如果是,dict那么您可以检查可以使用哪些键

print( data[0].keys() )

通过这种方式,您可以识别如何获得预期的元素。

您还可以使用json缩进来格式化它并查看它的外观

import json

print( json.dumps(data, indent=2) )

结果:

[
  {
    "_id": "5f563c1bf8eaa9d98eca231f",
    "allEnabledDs": null,
    "allEnabledIdSor": null,
    "correlationFilterEntitySource": true,
    "created_at": "2020-09-07T13:56:43.469Z",
    "dsConnectionList": null,
    "folderToLabelMapping": null,
    "idConnectionList": null,
    "identityResolutionScan": false,
    "info": null,
    "isCustomScanProfile": null,
    "modelId": null,
    "name": "Identity Discovery Scan",
    "origin": "Identity Discovery Scan",
    "scan_progress_status": {
      "Started": "2020-09-07T13:56:43.469Z"
    },
    "shouldCreateClassifiers": null,
    "skipIdScan": null,
    "state": "Started",
    "type": "identityDiscoveryScan",
    "updated_at": "2020-09-07T16:59:45.294Z",
    "identities_scanned": 0,
    "correlation_completed": true,
    "correlation_completed_dt": "2020-09-07T13:56:43.547Z",
    "piisummary_completed_dt": "2020-09-07T13:56:43.642Z",
    "stopRequested": true
  }
]

您可以使用类似的方式pprint(Pretty Print)

import pprint

pprint.pprint(data)

结果:

[{'_id': '5f563c1bf8eaa9d98eca231f',
  'allEnabledDs': None,
  'allEnabledIdSor': None,
  'correlationFilterEntitySource': True,
  'correlation_completed': True,
  'correlation_completed_dt': '2020-09-07T13:56:43.547Z',
  'created_at': '2020-09-07T13:56:43.469Z',
  'dsConnectionList': None,
  'folderToLabelMapping': None,
  'idConnectionList': None,
  'identities_scanned': 0,
  'identityResolutionScan': False,
  'info': None,
  'isCustomScanProfile': None,
  'modelId': None,
  'name': 'Identity Discovery Scan',
  'origin': 'Identity Discovery Scan',
  'piisummary_completed_dt': '2020-09-07T13:56:43.642Z',
  'scan_progress_status': {'Started': '2020-09-07T13:56:43.469Z'},
  'shouldCreateClassifiers': None,
  'skipIdScan': None,
  'state': 'Started',
  'stopRequested': True,
  'type': 'identityDiscoveryScan',
  'updated_at': '2020-09-07T16:59:45.294Z'}]

推荐阅读