Convert XML Data to JSON Servicenow Integration
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-09-2023 04:53 AM
How to convert XML data to JSON in ServiceNow Integration
var xmldata = 'XML Response';
var xmlDoc = new XMLDocument2(); // Servicenow API used to parse XML
xmlDoc.parseXML(xmldata); // XML Parsed
var xmltostring = xmlDoc.toString(); // Need to convert XML data to string first
var parsedXML= gs.xmlToJSON(xmltostring); // Servicenow GlideSystem API used to convert string XML data to JSON Object
var JSONTostring = JSON.stringify(parsedXML);
var parseXMl = JSON.parse(JSONTostring);
// get your appropriate object (Key Value) using json (parseXMl ) object
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-09-2023 05:54 AM
To convert XML data to JSON in ServiceNow Integration, you can use the following code snippet:
var xmldata = 'XML Response'; // replace with your XML data
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmldata, "text/xml");
var json = {};
var node = xmlDoc.firstChild;
if (node) {
json[node.nodeName] = xmlToJson(node);
}
function xmlToJson(xml) {
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(json[nodeName]) == "undefined") {
json[nodeName] = xmlToJson(item);
} else {
if (typeof(json[nodeName].push) == "undefined") {
var old = json[nodeName];
json[nodeName] = [];
json[nodeName].push(old);
}
json[nodeName].push(xmlToJson(item));
}
}
}
return json;
}
var jsonString = JSON.stringify(json);
This code creates an XML document object using the DOMParser API, and then uses a recursive function to convert the XML data to a JSON object. Finally, the JSON object is converted to a JSON string using JSON.stringify(). You can modify the code as needed to fit your specific use case.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-09-2023 11:06 AM
Most of the time you can write:
var o = gs.xmlToJSON(xmldata);
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-14-2023 07:14 AM - edited 11-08-2024 04:37 AM
Hi @gajananvw I have been facing the same problem, I even try
new XMLDocument2();
After that I created My own JS code to extract with attributes in Scoped APP
var XmlToJson = Class.create();
XmlToJson.prototype = {
initialize: function() {},
convert: function(xml) {
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xml);
var root = xmlDoc.getDocumentElement();
if (!root) {
gs.error("Root element is null. Unable to parse XML.");
return null;
}
var jsonResult = {};
jsonResult[root.getNodeName()] = this.parseXmlToJson(root);
return jsonResult;
},
isEmptyObject: function(obj) {
return Object.keys(obj).length === 0;
},
parseXmlToJson: function(node) {
if (!node) return null; // Check if node is null
var jsonObject = {};
// Get attributes (if any) with a null check
var attrs = node.getAttributes();
if (!this.isEmptyObject(attrs)) {
jsonObject = attrs;
}
// Iterate through child nodes
var childNodes = node.getChildNodeIterator();
if (childNodes.hasNext()) {
while (childNodes.hasNext()) {
var childNode = childNodes.next();
var childName = childNode.getNodeName();
var childValue = childNode.getNodeValue();
// Skip text nodes
if (childName === "#text") {
if (!this.isEmptyObject(attrs)) {
jsonObject['value'] = childValue || null;
} else {
jsonObject = childValue || null;
}
continue;
};
if (childNode.isCDATANode()) {
jsonObject[childName] = childValue;
} else if (!jsonObject[childName]) {
jsonObject[childName] = this.parseXmlToJson(childNode);
} else {
// Handle cases where there are multiple nodes with the same name
if (!Array.isArray(jsonObject[childName])) {
jsonObject[childName] = [jsonObject[childName]];
}
jsonObject[childName].push(this.parseXmlToJson(childNode));
}
}
} else if (this.isEmptyObject(attrs)) {
// If there are no child nodes, get the node's value
jsonObject = node.getNodeValue() || null;
}
return jsonObject;
},
type: 'XmlToJson'
};
var xml = "XML paylod";
gs.info(JSON.stringify(new XmlToJson().convert(xml), null, 2))
You can pass string XML.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
07-31-2024 07:41 AM
If you want the other way around, object to xml, you can use this code 🙂
convertObjToXML(obj){
var xml = '';
for (var prop in obj) {
xml += obj[prop] instanceof Array ? '' : "<" + prop + ">";
if (obj[prop] instanceof Array) {
for (var array in obj[prop]) {
xml += "<" + prop + ">";
xml += OBJtoXML(new Object(obj[prop][array]));
xml += "</" + prop + ">";
}
} else if (typeof obj[prop] == "object") {
xml += OBJtoXML(new Object(obj[prop]));
} else {
xml += obj[prop];
}
xml += obj[prop] instanceof Array ? '' : "</" + prop + ">";
}
var xml = xml.replace(/<\/?[0-9]{1,}>/g, '');
return xml
}