Home > database >  How to find value within a nested dictionary?
How to find value within a nested dictionary?

Time:08-18

I have an API response returning the following json:

{
    "statusCode": 200,
    "statusText": "Ok",
    "data": {
        "testId": "2278816_AklcAQ_E6B",
        "jsonUrl": "https://www.webpagetest.org/jsonResult.php?test=2278816_AklcAQ_E6B",
        "xmlUrl": "https://www.webpagetest.org/xmlResult/2278816_AklcAQ_E6B/",
        "userUrl": "https://www.webpagetest.org/result/2278816_AklcAQ_E6B/",
        "summaryCSV": "https://www.webpagetest.org/result/2278816_AklcAQ_E6B/page_data.csv",
        "detailCSV": "https://www.webpagetest.org/result/2278816_AklcAQ_E6B/requests.csv",
    },
}

I then parse this into a dictionary:

json_data = json.loads(response.text)
  • now from here what I need to do is find the value of key 'testId', and store that in a variable.

But I've tried a load of things and I can't get it working, I think the nested nature of this is making it harder (total newbie here)

Thanks

CodePudding user response:

Try the following (assuming you have the json you have written in the file temp.json) or coming from a request for that matter:

import json

# Write code to read a json file and convert to Python dictionary
with open('temp.json') as f:
    json_data = json.load(f)

print(json_data["data"]["testId"])
  • Related