I have particular field – "dataQuery". I want to move the entire content inside this field to one level up and finally delete this key itself. The original JSON is nested and can be upto 3-4MB in size. What are some possible ways to do this ?
As an example the following JSON:
{
"name": "John",
"age": 25,
"value": {
"dataQuery": {
"nestedField1": "value1",
"duplicateKey": "value1",
"dataQuery": {
"nestedField2": "value3",
"duplicateKey": "value2"
}
},
"child": [{
"nestedField3": {
"dataQuery": {
"nestedField4": "value4"
}
}
}]
}
}
should be transformed to the following:
{
"name": "John",
"age": 25,
"value": {
"nestedField1": "value1",
"nestedField2": "value3",
"duplicateKey": "value2"
,
"child": [{
"nestedField3": {
"nestedField4": "value4"
}
}]
}
}
2
Answers
How about something like:
You could use recursion to iterate through every object/array (
obj
) and compare the reference key (refKey
) to the target key (targetKey
).If your reference key is the target key (
targetKey
), assign the current object (obj
) to the parent (parent
) and delete the target key (targetKey
) off of the parent (parent
).The recursion is done before the removal occurs (post-order traversal).
Output