This code will help us to convert XML files to JSON. Using this script snippet You can easily convert XML data to JSON format. This will apply in SOAP-based integration(XML based response converting to JSON)
require(['N/xml'], function (xmlMod) {
//This function refer to https://davidwalsh.name/convert-xml-json
function xmlToJson(xmlNode) {
// Create the return object
var obj = Object.create(null);
if (xmlNode.nodeType == xmlMod.NodeType.ELEMENT_NODE) { // element
// do attributes
if (xmlNode.hasAttributes()) {
obj['@attributes'] = Object.create(null);
for (var j in xmlNode.attributes) {
if(xmlNode.hasAttribute({name : j})){
obj['@attributes'][j] = xmlNode.getAttribute({
name : j
});
}
}
}
} else if (xmlNode.nodeType == xmlMod.NodeType.TEXT_NODE) { // text
obj = xmlNode.nodeValue;
}
// do children
if (xmlNode.hasChildNodes()) {
for (var i = 0, childLen = xmlNode.childNodes.length; i < childLen; i++) {
var childItem = xmlNode.childNodes[i];
var nodeName = childItem.nodeName;
if (nodeName in obj) {
if (!Array.isArray(obj[nodeName])) {
obj[nodeName] = [
obj[nodeName]
];
}
obj[nodeName].push(xmlToJson(childItem));
} else {
obj[nodeName] = xmlToJson(childItem);
}
}
}
return obj;
};
var str = 'xml string';
var xmlObj = xmlMod.Parser.fromString({
text: str
});
var jsonObj = xmlToJson(xmlObj.documentElement);
log.debug('jsonObj', jsonObj);
});