I need to convert an XML file into a JSON ... anyo...
# suitescript
d
I need to convert an XML file into a JSON ... anyone done this? Is there a library or something I can use? Most of the libraries I've tried required the use of a browser (
document
). This need to be done server side. I was successful in using
X2JS
in SS1, but not so much in SS2. Any help/advice?
s
I have mentioned this here many times, but the library I've liked the most is JSONIX
d
I'll check it out, thanks @stalbert
a
@darrenhillconsulting You can do that with the native
N/xml
module...
Copy code
/**
 * Builds and return an Object from a given XML Data/String.
 *
 * @param {string} paramXMLNode
 *
 * @return {Object}
 * */
function xmlToJson(paramXMLNode) {

    var oXMLData = {};

    if (paramXMLNode.nodeType === xml.NodeType.ELEMENT_NODE) {

        if (paramXMLNode.hasAttributes()) {

            oXMLData['@attributes'] = {};

            for (var sAttribute in paramXMLNode.attributes) {

                if(paramXMLNode.hasAttribute({name : sAttribute})){
                    oXMLData['@attributes'][sAttribute] = paramXMLNode.getAttribute({
                        name : sAttribute
                    });
                }
            }
        }

    } else if (paramXMLNode.nodeType === xml.NodeType.TEXT_NODE) {

        oXMLData = paramXMLNode.nodeValue;
    }

    if (paramXMLNode.hasChildNodes()) {
        for (var nChild = 0; nChild < paramXMLNode.childNodes.length; nChild++) {

            var childItem = paramXMLNode.childNodes[nChild];
            var nodeName = childItem.nodeName;

            if (oXMLData.hasOwnProperty(nodeName)) {

                if (!Array.isArray(oXMLData[nodeName])) {

                    oXMLData[nodeName] = [oXMLData[nodeName]];
                }

                oXMLData[nodeName].push(xmlToJson(childItem));

            } else {

                oXMLData[nodeName] = xmlToJson(childItem);
            }
        }
    }

    return oXMLData;
}
Old function but it works pretty well...
d
I did start attempting this myself, but I'll give this a go @alien4u. Thanks!