Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  82] [ 7]  / answers: 1 / hits: 40970  / 6 Years ago, wed, february 14, 2018, 12:00:00

I am trying to convert the JSON to XML but not getting exact output.In My JSON having array object it not converting that to XML array.Mainly array object is not converting into XML as expected



var InputJSON = {body:{entry: [{ fullURL : abcd,Resource: 1234},{ fullURL : efgh,Resource: 5678}]}};
var output = eval(OBJtoXML(+InputJSON+);)

function OBJtoXML(obj) {
var xml = '';
for (var prop in obj) {
xml += < + prop + >;
if(obj[prop] instanceof Array) {
for (var array in obj[prop]) {
xml += OBJtoXML(new Object(obj[prop][array]));
}
} else if (typeof obj[prop] == object) {
xml += OBJtoXML(new Object(obj[prop]));
} else {
xml += obj[prop];
}
xml += </ + prop + >;
}
var xml = xml.replace(/</?[0-9]{1,}>/g,'');
return xml
}


Actual Output:



<body>
<entry>
<fullURL>abcd</fullURL>
<Resource>1234</Resource>
<fullURL>efgh</fullURL>
<Resource>5678</Resource>
</entry>
</body>


Expected Output:



<body>
<entry>
<fullURL>abcd</fullURL>
<Resource>1234</Resource>
</entry>
<entry>
<fullURL>efgh</fullURL>
<Resource>5678</Resource>
</entry>
</body>


Please guide me if i am missing anything from the code to get my expected result


More From » arrays

 Answers
3

replace your OBJtoXML function with



function OBJtoXML(obj) {
var xml = '';
for (var prop in obj) {
xml += obj[prop] instanceof Array ? '' : < + prop + >;
if (obj[prop] instanceof Array) {
for (var array in obj[prop]) {
xml += < + prop + >;
xml += OBJtoXML(new Object(obj[prop][array]));
xml += </ + prop + >;
}
} else if (typeof obj[prop] == object) {
xml += OBJtoXML(new Object(obj[prop]));
} else {
xml += obj[prop];
}
xml += obj[prop] instanceof Array ? '' : </ + prop + >;
}
var xml = xml.replace(/</?[0-9]{1,}>/g, '');
return xml
}

[#55151] Monday, February 12, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
estefanib

Total Points: 508
Total Questions: 104
Total Answers: 83

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
;