Convert XML To JSON (and Back) Using Javascript


Answer :

I think this is the best one: Converting between XML and JSON



Be sure to read the accompanying article on the xml.com O'Reilly site, which goes into details of the problems with these conversions, which I think you will find enlightening. The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit.



https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/):



This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and doesn't require any other additional libraries.


API functions



  • new X2JS() - to create your instance to access all library functionality. Also you could specify optional configuration options here

  • X2JS.xml2json - Convert XML specified as DOM Object to JSON

  • X2JS.json2xml - Convert JSON to XML DOM Object

  • X2JS.xml_str2json - Convert XML specified as string to JSON

  • X2JS.json2xml_str - Convert JSON to XML string



Online Demo on http://jsfiddle.net/abdmob/gkxucxrj/1/


var x2js = new X2JS();
function convertXml2JSon() {
$("#jsonArea").val(JSON.stringify(x2js.xml_str2json($("#xmlArea").val())));
}

function convertJSon2XML() {
$("#xmlArea").val(x2js.json2xml_str($.parseJSON($("#jsonArea").val())));
}

convertXml2JSon();
convertJSon2XML();
$("#convertToJsonBtn").click(convertXml2JSon);
$("#convertToXmlBtn").click(convertJSon2XML);


These answers helped me a lot to make this function:



function xml2json(xml) {
try {
var obj = {};
if (xml.children.length > 0) {
for (var i = 0; i < xml.children.length; i++) {
var item = xml.children.item(i);
var nodeName = item.nodeName;

if (typeof (obj[nodeName]) == "undefined") {
obj[nodeName] = xml2json(item);
} else {
if (typeof (obj[nodeName].push) == "undefined") {
var old = obj[nodeName];

obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xml2json(item));
}
}
} else {
obj = xml.textContent;
}
return obj;
} catch (e) {
console.log(e.message);
}
}


As long as you pass in a jquery dom/xml object: for me it was:



Jquery(this).find('content').eq(0)[0]


where content was the field I was storing my xml in.



Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android SDK Location Should Not Contain Whitespace, As This Cause Problems With NDK Tools