I want to convert my JSON to a specific format but not sure what is the best way. I want to make a generic function which I can use commonly. I do not want some code which has hard coded value such as root, Amount, etc.
I am using typeScript and node.
Current:
{
"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:
{
"root": {
"Amount": "1.00",
"Discount": "0.00"
}
}
Attempt-1: . This is not neat approach. So I do not like it.
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: This comes as null
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] );
}