0

Suppose I have a JSON file like this

     
{
    "A": 0,
    "B": {
        "display": "B Value",
        "key": 2,
        "name": "random name",
        "url": "https://www.google.com"
    },
    "C": "C-Value",
    "D": {
        "label": "value",
        "value": "value"
    },
    "X": null
}

And I have a list, which contains the keys, the keys are of different name and depth. I want to get the value corresponding to each key.

keys = [
    ("B", "display"),
    ("C"),
    ("D", "label"),
    ("X", "Y", "Z")
]

I first opened the json file, used json.load() to convert it to dict, then tried to use double for loop to parse the data, but I am not sure how to use something like dict[key1][key2]... where there could be variable number of keys for each item in keys.

with open("sample.json") as json_file:
    json_data = json.load(json_file)
    for item in keys:
        print(json_data[item])

This is giving me KeyError

0 Answers0