I have a json object like so
{
"scenefile": {
"globaldata": {
"diffusecoeff": {
"v": "0.5"
},
"specularcoeff": {
"v": "0.5"
},
"ambientcoeff": {
"v": "0.5"
}
},
"cameradata": { ... },
"lightdata": [
{"light1":
{"strength": {"value": 5}}
},
{"light2":
{"strength": {"value": 10}}
}
]
}
}
My issue is that I want to get rid of the "v" keys. So it would become
{
"scenefile": {
"globaldata": {
"diffusecoeff": "0.5",
"specularcoeff": "0.5",
"ambientcoeff": "0.5"
},
"cameradata": {
...
},
"lightdata": [
{"light1": {"strength": 5}},
{"light2": {"strength": 10}}
]
}
}
What is stumping me is that there are several cases of
"attribute": {
"v": someValue
}
All throughout the nested json file (not just in the format mentioned above), and so I am looking for a way to quickly change all of those to just be
"attribute": someValue
2
Answers
Just loop over the elements of that one dictionary, replacing each value with the nested
v
key’s value.Output:
This doesn’t touch the rest of the dictionary, so other
v
keys are left alone.Use a recursive function.
If the parameter is a dictionary, loop over its elements. If any of them is a dictionary with just one element, and the key begins with
v
, replace the dictionary with the nested value. Otherwise, recurse into the value.If the parameter is a list, iterate over its elements and recurse into each element.