I've found several subpar answers out there, and the only ones that seem to be reliable require CommonJS.
Is there any way for my iOS app to convert XML to JSON without using CommonJS?
2 Answers
function xmlToJson(xml) { var attr, child, attrs = xml.attributes, children = xml.childNodes, key = xml.nodeType, obj = {}, i = -1; if(attrs && key == 1 && attrs.length) { obj[ key = '@attributes'] = {}; while( attr = attrs.item(++i)) { obj[key][attr.nodeName] = attr.nodeValue; } i = -1; } else if(key == 3) { obj = xml.nodeValue; } for ( var i = 0; i < children.length; i++) { var child = children.item(i); key = child.nodeName; if(obj.hasOwnProperty(key)) { if(obj.toString.call(obj[key]) != '[object Array]') { obj[key] = [obj[key]]; } obj[key].push(xmlToJson(child)); } else { obj[key] = xmlToJson(child); } } return obj; }found this lying around on my computer... think it works
commonJS is a just a way to structure code. The code you end up with for the conversion process should be the same. I googled "convert xml to json using javascript" and got a bunch of results. The first result pertained to titanium. Here is the link.
Your Answer
Think you can help? Login to answer this question!