Home > Software design >  loop over a list of json dictionary objects to return values
loop over a list of json dictionary objects to return values

Time:02-18

This command in python returns the below image:

incidents = res[0].get("Contents", [{}])
return_results(incidents)

enter image description here

I want to iterate over the data objects and pull back values.

Such as:

for incident in incidents:
    lowestLevel = incident.get("Contents", {}).get("data")
    return_results(lowestLevel.get('id'))

I can't figure how to loop over the data to get the id for each "data set"

Anyone have any thoughts, let me know what I can expand on,

Thanks,

Boyd

CodePudding user response:

In the screenshot, the incidents have 2 values. I do think the data you needed is inside the root.data. you need something like for looping for item in lowestlevel['root']['data']:

CodePudding user response:

If incidents = res[0].get("Contents", [{}]) and for incident in incidents: are both talking about the same incidents then it looks as though you are iterating over the dictionary (JSON) Objects in an array.

For your implementation would the following suffice?:

for incident in incidents:
    for lowestLevel in incident.values():
        data = lowestLevel.get("data")
        return_results(data.get("id"))

Also here are suggested looping techniques available in python's documentation.

  • Related