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 converti
There are a few problems here, for starters, here the JSON string variable either needs to have it's quotes escaped. Or be wrapped in single quotes. For example:
var InputJSON = '{"body":{"entry": [{ "fullURL" : "abcd","Resource": "1234"},{ "fullURL" : "efgh","Resource": "5678"}]}}';
Next, there is no need to use eval
here, when using JSON in JavaScript you should use JSON.parse
// First parse the JSON
var InputJSON = JSON.parse(InputJSON);
// Now execute the 'OBJtoXML' function
var output = OBJtoXML(InputJSON);
Now we come to the meat of this question, why is entry
only occuring once?
The problem that you're having is that xml += "<" + prop + ">";
and xml += "" + prop + ">";
are only happening once per property.
A possible solution would look like this:
function OBJtoXML(obj) {
var xml = '';
for (var prop in obj) {
xml += "<" + prop + ">";
if(Array.isArray(obj[prop])) {
for (var array of obj[prop]) {
// A real botch fix here
xml += "" + prop + ">";
xml += "<" + prop + ">";
xml += OBJtoXML(new Object(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
}