Convert XML Request to JSON
This example details how to convert XML responses generated from a Services Workbench script to JSON and then back to XML using Designer .js
scripts.
-
Custom
.js
functions are written for the conversion of XML to JSON and JSON to XML. in javascript (.js) file. -
In a Services Workbench script, the response data is stored in locker so that it can be retrieved and used in Designer
.js
script. -
The Designer
.js
script includes the previous two files, and once the data is retrieved from locker, uses the custom.js
function to parse the XML back to JSON and perform the required validations.
XML to JSON Function
Converts XML to JSON and JSON to XML.
Sample Script
/**
* @aiq.webdesigner
* This script requires AIQ Web Designer
*/
function jsonToXml(obj) {
// create xml string
var xml = '';//'<?xml version="1.0" encoding="UTF-8"?>';
//loop through and add each property as a an xml tag as well as sub properties
for (var prop in obj) {
if (!obj.hasOwnProperty(prop)) {
continue;
}
if (obj[prop] == undefined)
continue;
xml += "<" + prop + ">";
if (typeof obj[prop] == "object")
xml += jsonToXml(new Object(obj[prop]));
else
xml += convertXMLString(obj[prop], 'xml');
xml += "</" + prop + ">";
}
// searches the string for numbers surrounded by underscores and removes them; used for multiple properties in the json that are set up an an object instead of an array
let reducedXML = xml.replace(/([_]\d)\w+/g, '');
return reducedXML;
}
function convertXMLString(input, outputFormat){
if(typeof input === 'string'){
if(outputFormat === 'xml'){
return input.replace(/(&)/g, '&').replace(/(<)/g, '<').replace(/(>)/g, '>').replace(/(')/g, ''')
} else if(outputFormat === 'string'){
return input.replace(/(<)/g, '<').replace(/(>)/g, '>').replace(/(')/g, "'").replace(/(&)/g, '&')
} else {
// invalid outputFormat
return input;
}
} else {
// not a stringF
return input;
}
}
function parseXmlToJson(xmlString) {
let xmlToParse = xmlString.replace(/[\r\n']/g, match => match === "'" ? "\\'" : ' '); // Replce all the new line and single quote
const json = evalAndReturn(`
const parser = new DOMParser();
const xml = parser.parseFromString('${xmlToParse}', "application/xml");
if (xml.getElementsByTagName("parsererror").length) {
return 'Error';
}
const parseXmlToJson = (xml) => {
let obj = {};
let nodeName = xml.nodeName.includes(":") ? xml.nodeName.split(":")[1] : xml.nodeName;
if (xml.childNodes.length === 1 && xml.firstChild.nodeType === 3) {
return xml.textContent.trim();
}
for (let child of xml.childNodes) {
if (child.nodeType === 3 && !child.textContent.trim()) {
continue; // Ignore whitespace text nodes
}
let childName = child.nodeName.includes(":") ? child.nodeName.split(":")[1] : child.nodeName;
let childJson = parseXmlToJson(child);
if (obj[childName]) {
if (!Array.isArray(obj[childName])) {
obj[childName] = [obj[childName]];
}
obj[childName].push(childJson);
} else {
obj[childName] = childJson;
}
}
return obj;
}
const jsonObj = parseXmlToJson(xml);
return JSON.stringify(jsonObj);
`)
return json;
}
Services Workbench Script
The response data is stored in locker so that it can be retrieved and used in a Designer .js
script.
Sample Script
/**
* @aiq.servicesworkbench
* This script requires Services Workbench
*/
var resp = get("https://mocktarget.apigee.net/xml");
var responseData = resp.getDataString();
//log(responseData);
locker.put("XMLData",responseData);
Designer Script
Includes the previous two scripts, and once the data is retrieved from locker, uses the custom .js
function to parse the XML back to JSON and perform the required validations.
Sample Script
/**
* @aiq.webdesigner
* This script requires AIQ Web Designer
*/
include("{ds}/XMLtoJSON&ObjtoXML.js");
serviceSuite('{ds}/XMLJSON.js');
var xmlString = retrieve("XMLData");
log(xmlString);
var jsondata = parseXmlToJson(xmlString);
log(jsondata);
log(JSON.parse(jsondata));
var jsonD = JSON.parse(jsondata);
log(jsonToXml(JSON.parse(jsondata)));
assertEquals("John",jsonD.root.firstName);
-
Lines 5 through 8 : Includes the common JavaScript and Service Workbench scripts. Retrieves the data from the locker and store in a variable.
-
Lines 9 through 11 : Uses the
parseXmlToJson
function to convert the response XML to JSON string. Next line it can be parsed and converted to JSON object, from which validations can be performed by extracting the required data. -
Line 13 : JSON to XML conversion is done using the
JsonToXml
function.
Resources : Sample Scripts
You can download the sample scripts from these links.