I pulled this function from another stackoverflow question(link below). I want to be able to convert the XML that I have(included as a HTML comment) to a JSON format. I thought this snippet would work but it keeps giving this error:
Uncaught TypeError: Object cat.xml has no method 'hasChildNodes'
I still trying wrap my head around javascript so I can't figure this out. I am sorry if this has been answered but I searched and can't find an answer anywhere.Here is the original question
Tool (javascript) to convert a XML string to JSON
and here is a jsbin with what I am trying to do and with the error showing. Thank you.
http://jsbin.com/ujoPECU/1/edit
var xmlToJson = function (xml) {
'use strict';
var obj = {};
if (xml.nodeType == 1) {
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) {
obj = xml.nodeValue;
}
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof (obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof (obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
var jsonText = JSON.stringify(xmlToJson("cat.xml")); // xmlDoc = xml dom document
console.log(jsonText);
xmlToJson()function doesn't return JSON, it returns an object (which you seem to already know given you've usedJSON.stringify()to get actual JSON from the result).