What does this line do? (xml2json conversion in javascript)

662 views Asked by At

Hi I have found a method on-line for converting XML to JSON. I have been using it for a bit and it works well. Now I need to modify it to meet my specific needs but modifying it is difficult because I do not completely understand what this method is doing line per line. Specifically the following line.

if (typeof(obj[nodeName].push) == "undefined" )

I am clueless. I believe this operation is being done on a NodeList which only has a single method, and that is not it.

If it helps here is the entire method

function xmlToJsonHelper(xml) {


// Create the return object
var obj = {};
console.log(typeof(xml))

if (xml.nodeType == 1) { // element
    // do attributes
    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 ) { // text
    obj = xml.nodeValue;
}

// do children
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" ) {
            if(xml.childNodes[i].nodeType != 3 || !xml.childNodes[i].data.match("\\n"))

                obj[nodeName] = xmlToJsonHelper(item); //modded to call helper
        } 
        else {
            if (typeof(obj[nodeName].push) == "undefined" ) {
                var old = obj[nodeName];
                obj[nodeName] = [];
                obj[nodeName].push(old);
            }
            obj[nodeName].push(xmlToJsonHelper(item));//modded to call helper
        }
    }
}
return obj;     

};

1

There are 1 answers

0
tom creighton On BEST ANSWER

It looks like it's testing if the element in the obj object is an array.

From the quick look at the code you provided it looks like this method goes over elements in xml and tries to build a JSON object (obj) with the same node nesting. So something like

<ants>
   <hill></hill>
   <picnic></picnic>
</ants>

will look like

{
   ants: [
           {hill:...}, 
           {picnic:...}
         ]
}

The test for obj[nodeName].push is just asking of the element in obj[nodeName] has the function push, meaning it's an array. If not, then it takes the value out, makes the new value an empty array, and then pushes the old value into the array.