Reputation: 75
I have the following JSON Array. If device['name'] = 'DJ'
, then I want to retrieve the entire json array from event_location to sum_text, otherwise i do not want that array.
{
"results": [
{
"event_location": "San Jose",
"event_type": "Party",
"source_type": [
"COMPANY",
"CONSUM"
],
"device": [
{
"name": "DJ",
"date_order": "20210120",
"manufacturer_country": "USA"
}
],
"problems": [
"Material Rupture"
],
"zip_code": "",
"sum_text": [
{
"sum_text_key": "220229361",
"text_type_code": "Additional Manufacturer Narrative",
"text": "A REVIEW OF THE DEVICE HISTORY RECORD HAS BEEN INITIATED."
},
{
"sum_text_key": "220229362",
"text_type_code": "Description of Event or Problem",
"text": "DEVICE REPORTED RIGHT SIDE RUPTURE."
}
]
},
{
"event_location": "New York",
"event_type": "Baby Shower",
"source_type": [
"COMPANY",
"CONSUM"
],
"device": [
{
"name": "Musical Band",
"date_order": "20210120",
"manufacturer_country": "USA"
}
],
"problems": [
"Material Rupture"
],
"zip_code": "",
"sum_text": [
{
"sum_text_key": "220229361",
"text_type_code": "Additional Manufacturer Narrative",
"text": "A REVIEW OF THE DEVICE HISTORY RECORD HAS BEEN INITIATED."
},
{
"sum_text_key": "220229362",
"text_type_code": "Description of Event or Problem",
"text": "DEVICE REPORTED RIGHT SIDE RUPTURE."
}
]
},
{
"event_location": "Boston",
"event_type": "Wedding",
"source_type": [
"COMPANY",
"CONSUM"
],
"device": [
{
"name": "Soft Music Band",
"date_order": "20210120",
"manufacturer_country": "USA"
}
],
"problems": [
"Material Rupture"
],
"zip_code": "",
"sum_text": [
{
"sum_text_key": "220229361",
"text_type_code": "Additional Manufacturer Narrative",
"text": "A REVIEW OF THE DEVICE HISTORY RECORD HAS BEEN INITIATED."
},
{
"sum_text_key": "220229362",
"text_type_code": "Description of Event or Problem",
"text": "DEVICE REPORTED RIGHT SIDE RUPTURE."
}
]
}
]
}
How do I to iterate it so that I get only that particular array. Have tried to iterate it with for loop. But failing to retrieve the entire array.
Upvotes: 0
Views: 30
Reputation: 467
This should do the trick:
json = {...data here}
for event in json['results']:
for device in event['device']:
if device["name"] == "DJ":
print(event)
In the line print(event)
you can do whatever you want with the current event, append it to a list, return it, or whatever you require.
Also, note that device is a list
and not a dict
, so we iterate over all the devices to see if one of them matches the speficied name.
Upvotes: 2