JAVASCRIPT
Convert XML API Responses to JSON in JavaScript
Learn to parse and transform XML data received from legacy APIs into a more manageable JavaScript object (JSON equivalent), making it easier to integrate with modern web applications.
async function fetchXmlAndConvertToJson(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const xmlText = await response.text();
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlText, 'application/xml');
function xmlToJson(xml) {
let obj = {};
if (xml.nodeType === 1) { // element
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (let j = 0; j < xml.attributes.length; j++) {
let attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType === 3 || xml.nodeType === 4) { // text or CDATA
return xml.nodeValue.trim(); // Trim whitespace
}
// do children
if (xml.hasChildNodes()) {
for (let i = 0; i < xml.childNodes.length; i++) {
let item = xml.childNodes.item(i);
let nodeName = item.nodeName;
// Ignore text nodes that are purely whitespace between elements
if (item.nodeType === 3 && item.nodeValue.trim() === '') continue;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
let old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
}
// The root element might have attributes or children, process it.
const jsonOutput = xmlToJson(xmlDoc.documentElement);
return jsonOutput;
} catch (error) {
console.error('Error fetching or parsing XML:', error);
throw error;
}
}
// Example Usage:
// (async () => {
// try {
// // Example XML from w3schools.com/xml/note.xml
// const jsonOutput = await fetchXmlAndConvertToJson('https://www.w3schools.com/xml/note.xml');
// console.log(JSON.stringify(jsonOutput, null, 2));
// /* Expected output for <note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>:
// {
// "to": "Tove",
// "from": "Jani",
// "heading": "Reminder",
// "body": "Don't forget me this weekend!"
// }
// */
// } catch (e) {
// console.error(e);
// }
// })();
How it works: This JavaScript snippet provides a utility function to fetch XML data from an API and convert it into a JavaScript object, which is effectively JSON. It leverages the browser's native `DOMParser` to parse the XML string into a manipulable DOM structure. A recursive `xmlToJson` helper function then traverses the XML nodes, handling elements, attributes, and text content, and correctly converts repeated elements into arrays. This is essential for integrating with older or specialized APIs that still return data in XML format, making the data accessible and easier to work with in modern JavaScript applications.