Home > Software engineering >  Python extract only 'key' values in in nested JSON where 'value' is a dictionary
Python extract only 'key' values in in nested JSON where 'value' is a dictionary

Time:02-05

I have the folowing 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
    }
  ]
}

I need to get

11003,11005

as output (better if it could be save in csv).this is actually the data i'm getting off a webpage(using requests). super new to Json.. any help would be appreciated

CodePudding user response:

Assuming your global dictionary has been loaded in data you can extract the keys with a comprehension:

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

And you can easily write them into a csv file with:

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

CodePudding user response:

Use built-in json.loads(json: str) to parse json string to python dict.

  •  Tags:  
  • Related