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
JavaScript Object Notation This is generally true, but data can be compressed and formatted in such a way that XML and JSON are similar. Thus, JSON and XML really are interchangeable, though many modern developers prefer to use JSON.
If you'd like the JavaScript in string JSON format, you can code: // Assuming xmlDoc is the XML DOM Document var jsonText = JSON. stringify(xmlToJson(xmlDoc)); This function has been extremely useful in allowing me to quickly disregard XML and use JSON instead.
JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. Even though it closely resembles JavaScript object literal syntax, it can be used independently from JavaScript, and many programming environments feature the ability to read (parse) and generate JSON.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With