I want to process a nested JSON with an Azure Function and Python. The JSON has more than 3 sometimes up to 10 or more nested layers. this is a simple example of a JSON passed to the function:
[{
"node1": {
"tattr": {
"usqx": "qhi123"
},
"x-child": [{
"el1": "ast",
"tattr": {
"usx": "xht",
"ust": "cr12"
},
"x-child": [{
"el1": "asx",
"tattr": {
"usx": "md0"
},
"x-child": [{
"el1": "ast",
"tattr": {
"usx": "mdw"
},
"x-child": [{
"el1": "ast",
"tattr": {
"usx": "mdh"
},
"x-child": [{
"el1": "ast",
"x-child": "placeholder_a"
}]
}, {
"el1": "ast",
"tattr": {
"usx": "ssq"
},
"x-child": "placeholder_c"
}, {
"el1": "div",
"tattr": {
"usx": "mdf"
},
"x-child": "abc"
}]
}]
}]
}]
}
}, {
"node02": {
"tattr": {
"usx": "qhi123"
}
}
}]
In this example, placeholder_a
should be replaced.
Somewhere in this is a value that needs to be replaced. My idea is to recursive iterate the JSON and process every key that has a dict or list as value. I think the recursive call of the function with a part of the JSON string just copies the JSON. So if the searched string will be find and changed in one recursion, it does not change the original string. What is the best approach to get the "placeholder" in the JSON replaced? It can be on every level.
Since my approach seems to be wrong, I am looking for ideas how to solve the issue. Currently I am between a simple string replace, where I am not sure if the replaced string will be a key or value in a JSON or a recursive function that takes the JSON, search and replace and rebuild the JSON on every recusion.
The code finds the search_para
and replaces it but it will not be changed in the original string.
def lin(json_para,search_para,replace_para):
json_decoded = json.loads(json_para)
if isinstance(json_decoded,list):
for list_element in json_decoded:
lin(json.dumps(list_element))
elif isinstance(json_decoded,dict):
for dict_element in json_decoded:
if isinstance(json_decoded[dict_element],dict):
lin(json.dumps(json_decoded[dict_element]))
elif isinstance(json_decoded[dict_element],str):
if str(json_decoded[dict_element]) == 'search_para:
json_decoded[dict_element] = replace_para