Parse XML to JSON using NetSuite ‘N/xml’ module

Create a helper.js file so the function can be shared across different scripts.

/**
 * @NApiVersion 2.1
 */
/************************************************************************************************
 * * Parse XML **
 *
 *
 * **********************************************************************************************
 *
 * Author: Jobin and Jismi IT Services
 *
 * Date Created : 29-August-2022
 *
 * Created By: Manu Antony
 * 
 * Description : Custom module for parsing XML to JSON
 *
 * REVISION HISTORY
 *
 *
 *
 *
 ***********************************************************************************************/
define(["N/xml"], function (xmlModule) {


    const nsXMLToJSON = (xmlString) => {
        //*********** HELPER FUNCTIONS ***********
        const nsXMLToJSONDirty = (node) => {
            var obj = {};
            // @ts-ignore
            if (!'nodeType' in node) {
                return obj;
            }
            if (node.nodeType == 1 || node.nodeType == 'ELEMENT_NODE') {
                if (Object.keys(node.attributes).length > 0) {
                    obj["@attributes"] = {};
                    for (var j in node.attributes) {
                        var attribute = node.attributes[j];
                        if (attribute) {
                            obj["@attributes"][attribute.name] = attribute.value;
                        }
                    }
                }
            }
            else if (node.nodeType == 3 || node.nodeType == 'TEXT_NODE') {
                obj = node.nodeValue;
            }
            if (node.hasChildNodes()) {
                var childNodes = node.childNodes;
                for (var k in childNodes) {
                    var item = childNodes[k];
                    var nodeName = item.nodeName;
                    if (typeof (obj[nodeName]) == "undefined") {
                        obj[nodeName] = nsXMLToJSONDirty(item); //run the function again
                    }
                    else {
                        if (typeof (obj[nodeName].push) == "undefined") {
                            var old = obj[nodeName];
                            obj[nodeName] = [];
                            obj[nodeName].push(old);
                        }
                        obj[nodeName].push(nsXMLToJSONDirty(item));
                    }
                }
            }
            return obj;
        };
        const cleanObject = (myobj, recurse) => {
            var myobjcopy = JSON.parse(JSON.stringify(myobj));
            for (var i in myobjcopy) {
                if (recurse && typeof myobjcopy[i] === 'object') {
                    if (i == "#text") {
                        delete myobjcopy[i];
                    }
                    else {
                        //Check if it only contains a text object
                        if (Object.keys(myobjcopy[i]).length == 1) {
                            if (typeof myobjcopy[i]['#text'] != "undefined") {
                                if (myobjcopy[i]['#text'] || myobjcopy[i]['#text'] == 0) {
                                    myobjcopy[i] = myobjcopy[i]['#text'];
                                }
                            }
                        }
                        else {
                            //Handle empty objects
                            if (Object.keys(myobjcopy[i]).length == 0) {
                                myobjcopy[i] = undefined;
                            }
                        }
                        if (myobjcopy[i]) {
                            myobjcopy[i] = cleanObject(myobjcopy[i], recurse);
                        }
                    }
                }
            }
            return myobjcopy;
        };
        var xmlObj = xmlModule.Parser.fromString({
            text: xmlString
        });
        var obj = nsXMLToJSONDirty(xmlObj);
        return cleanObject(obj, true);
    };



    return {
        nsXMLToJSON: nsXMLToJSON
    }
});


import the helper file and use the xmlToJson function in your script.

define(['N/file', '/SuiteScripts/PATH_TO_HELPER_FILE/helper'], function(file, helper) {

    ...
    
    var string = file.load({ id: '/SuiteScripts/PATH_TO_FILE/filename.xml' }).getContents()
    var json_object = helper.nsXMLToJSON(string);
    
    ...
    
})

Leave a comment

Your email address will not be published. Required fields are marked *