I have a fairly nested json structure that I want to loop over and modify ID values based on a condition. Ideally the key names are not needed as they can be variable. My idea was to grab the Id value from the top level and then search for it throughout the json file and modify all the matching values as the ID value is always the same. The modification is simply adding "_001" to it. But the condition should be that it is only done in subdicts of "type": "A". See below an example json of the structure I am dealing with:
{
"name1": "test1",
"Id": "12345678",
"data": [
{
"type": "A",
"Id1": "12345678",
"level2": {
"name2": "test2",
"Id2": "12345678",
"level3": {
"name3": "test3",
"Id3": "12345678"
},
"Edit": [
{
"Id": "12345678",
"Bla": "XXXXXXXXXX"
},
{
"Id": "12345678",
"Bla": "XXXXXXXXX"
}
]
}
},
{
"type": "B",
"id": "12345678",
"data": {
"Id": "12345678",
"Name": "test6"
}
}
]
}
I want to loop over this json and replace the Id value in every instance inside the level1 if the "type" is equal to "A" otherwise no need to loop through that particular dict, meaning the IDs should not be modified. I would ideally check this id value at the top level and then filter by the value instead of the key, since the key could vary a bit (see at lowest level where its called "source_id"). So in the example json all Ids within the subdict with "type": "A" should be replaced, whereas the ones with "type": "B", should remain. As output I want to return the json in the same format just with the IDs changed.
The code I have so far still relies on knowledge of the key names and does not capture the Id in the "Edit" list of dicts, as I can not figure out to search for an ID value like "12345678" in a nested dict based on the mentioned type filter:
data = json.load(open("test.json"))
curr_id = data['Id']
new_id = curr_id + '_001')
for item in data['data']:
if item['type'] != 'B':
item['Id1'] = new_id
item['level2']['Id2'] = new_id
item['level2']['level3']['Id3'] = new_id