Looking for advice on how to efficiently convert JSON data into a specific format without hardcoding any values like "root" or "Amount". I want to create a reusable function that can be used in various scenarios. Currently, I am working with TypeScript and Node.js.
Current JSON:
{
"elements": [
{
"type": "element",
"name": "root",
"elements": [
{
"type": "element",
"name": "Amount",
"elements": [
{
"type": "text",
"text": "1.00"
}
]
},
{
"type": "element",
"name": "Discount",
"elements": [
{
"type": "text",
"text": "0.00"
}
]
}
]
}
]
}
Expected Output:
{
"root": {
"Amount": "1.00",
"Discount": "0.00"
}
}
Attempt-1: Tried this approach but not satisfied:
var newJsonData = convertedXml2json.replace(/"elements": /g, "").replace(/"type": "element",/g, "").replace(/"name":/g, "").replace(/"type": "text",/g, "").replace(/"text":/g, "").replace("[", "").replace("{", "");
console.log(newJsonData);
Attempt-2: Ended up with null
result:
var len = convertedXml2json.elements,
newData = {updatedJson:[]},
i;
for (i=0; i < len; i+=1) {
newData.updatedJson.push([convertedXml2json.elements[i].name, convertedXml2json.elements[i].elements[i].text]);
}