Python 仅提取嵌套 JSON 中的 'key' 值,其中 'value' 是列表中的字典

Python extract only 'key' values in in nested JSON where 'value' is a dictionary in a list

我有以下 Json:

    {
  "10208": [
    {
      "11003": {
        "totalExecutions": 1,
        "endDate": "",
        "description": "",
        "totalExecuted": 0,
        "started": "",
        "versionName": "v2",
        "expand": "executionSummaries",
        "projectKey": "TEST",
        "versionId": 10208,
        "modifiedBy": "",
        "projectId": 10203,
        "startDate": "",
        "executionSummaries": {
          "executionSummary": []
        }
      },
      "recordsCount": 1
    }
  ],
  "-1": [
    {
      "11005": {
        "totalExecutions": 2,
        "endDate": "",
        "description": "",
        "totalExecuted": 1,
        "started": "",
        "versionName": "Unscheduled",
        "expand": "executionSummaries",
        "modifiedBy": "",
        "projectId": 10203,
        "startDate": "",
        "executionSummaries": {
          "executionSummary": []
        }
      },
      "recordsCount": 1
    }
  ]
}

我需要

11003,11005

作为输出(如果可以保存在 csv 中则更好)。这实际上是我从网页上获取的数据(使用请求)。 Json 的超级新手。任何帮助将不胜感激

使用 built-in json.loads(json: str) 将 json 字符串解析为 python 字典。

假设您的全局词典已加载到 data 中,您可以通过理解提取键:

keys = [k for val in data.values() for d in val for k in d.keys()
    if k != 'recordsCount']

您可以轻松地将它们写入 csv 文件:

with open('file.csv', 'w', newline='') as fdout:
    wr = csv.writer(fdout)
    wr.writerow(keys)