I am trying to recursively parse a JSON object in JavaScript.
Below is an example of the JSON structure:
const obj = {
tag: 'AA',
type: 'constructed',
value: 'ABCD1',
child: [
{
tag: 'BB',
type: 'constructed',
value: 'ABCD2',
child: [
{
tag: 'CC',
type: 'constructed',
value: 'ABCD3',
child: [
{
tag: 'DD',
type: 'primitive',
value: 'ABCD4',
child: []
},
{
tag: 'EE',
type: 'constructed',
value: 'ABCD5',
child: [
{
tag: 'FF',
type: 'primitive',
value: 'ABCD6',
child: []
},
{
tag: 'GG',
type: 'primitive',
value: 'ABCD7',
child: []
}
]
},
{
tag: 'HH',
type: 'primitive',
value: 'ABCD8',
child: []
}
]
}
]
},
{
tag: 'II',
type: 'primitive',
value: 'ABCD9',
child: []
}
]
}
The desired output should resemble this format:
{
"AA": [
{
"BB": [
{
"CC": [
{
"DD": "ABCD4"
},
{
"EE": [
{
"FF": "ABCD6"
},
{
"GG": "ABCD7"
}
]
},
{
"HH": "ABCD8"
}
]
}
]
},
{
"II": "ABCD9"
}
]
}
The logic is that objects with type constructed
should be nested within another object, while those with type primitive
should directly have a key-value pair. The depth of the object can vary, and it may contain both constructed and primitive objects on the same level.
Currently, I have implemented the following code:
let jsonOutput = {}
parseData(obj, jsonOutput)
function parseData(jsonToParse, jsonOutput) {
const type = jsonToParse.type
const tag = jsonToParse.tag
const value = jsonToParse.value
let prev = jsonOutput
if (type === 'constructed') {
prev[tag] = []
return parseData(jsonToParse.child[0], prev[tag])
} else if (type === 'primitive') {
prev[tag] = value
return parseData(jsonToParse.child, prev[tag])
}
}
You can see my implementation in action at this fiddle: https://jsfiddle.net/kzaiwo/0v6a2tp8/16/
However, I'm struggling to make it iterate through the entire object. Recursion is not my forte, but I believe it's the most efficient way to handle this task. Can someone please assist me in finding what I'm missing? Any help would be greatly appreciated!
Thank you!