1

I have a slightly more complex than posted function which loops through JSON data. But the problem should be apparent here.

The for loop only looks through the very first row of the JSON data, which does not have the parameter I'm seeking, and so it stops immediately after parsing the very first row of the JSON data. I would like for it to continue looping through each row in the data until it finds the value_id I pass in, which does exist the JSON data some many rows down.

Is there some simple modification I'm missing here that can make this possible?

def get_values(value_id):
    identifier = None
    data = api_grabber.get_value_data()
    for row in data["data"]:
        if row["department"]["segment"]["data"]["id"] == value_id
            break
    if identifier is None:
        return
init200
  • 23
  • 3

1 Answers1

0

You have to recursively search the JSON object to find the required key. The code searches all levels to find the matching key. The below code is adapted from this Stack answer.

def get_values(json_input, lookup_key):
    if isinstance(json_input, dict):
        for k, v in json_input.items():
            if k == lookup_key:
                yield v
            else:
                yield from get_values(v, lookup_key)
    elif isinstance(json_input, list):
        for item in json_input:
            yield from get_values(item, lookup_key)

For example,

dict_test = {
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
    "batters":
        {
            "batter":
                [
                    { "id": "1001", "type": "Regular" },
                    { "id": "1002", "type": "Chocolate" },
                    { "id": "1003", "type": "Blueberry" },
                    { "id": "1004", "type": "Devil's Food" }
                ]
        },
    "topping":
        [
            { "id": "5001", "type": "None" },
            { "id": "5002", "type": "Glazed" },
            { "id": "5005", "type": "Sugar" },
            { "id": "5007", "type": "Powdered Sugar" },
            { "id": "5006", "type": "Chocolate with Sprinkles" },
            { "id": "5003", "type": "Chocolate" },
            { "id": "5004", "type": "Maple" }
        ]
}

print(list(get_values(dict_test, "id")))

Output:

['0001',
 '1001',
 '1002',
 '1003',
 '1004',
 '5001',
 '5002',
 '5005',
 '5007',
 '5006',
 '5003',
 '5004']

The above output shows the matching values for the key id in all levels.

Kabilan Mohanraj
  • 1,856
  • 1
  • 7
  • 17