JAVASCRIPT
Convert XML API Responses to JSON in Node.js
Process and transform XML data received from legacy APIs into a more manageable JSON format using the 'xml2js' library in Node.js for easier consumption.
const axios = require('axios');
const { parseStringPromise } = require('xml2js');
async function fetchAndConvertXmlToJson(xmlApiUrl) {
try {
// In a real scenario, xmlApiUrl would be something like 'https://example.com/api/data.xml'
// For this demonstration, we'll simulate a fetch to a mock XML string.
const mockXmlResponse = `
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
`;
// For a real API call, use: const response = await axios.get(xmlApiUrl);
// For this example, we'll directly use the mock XML string.
// const xmlData = response.data;
const xmlData = mockXmlResponse;
// Convert XML string to JavaScript object (JSON equivalent)
const jsonData = await parseStringPromise(xmlData, { explicitArray: false, mergeAttrs: true });
console.log('Original XML:
', xmlData);
console.log('
Converted JSON:
', JSON.stringify(jsonData, null, 2));
return jsonData;
} catch (error) {
console.error('Error fetching or parsing XML:', error.message);
throw error;
}
}
// To run this example, you need to install axios and xml2js:
// npm install axios xml2js
// Example Usage:
fetchAndConvertXmlToJson('https://mock.api.com/data.xml') // The URL here is just a placeholder for the demo
.then(json => console.log('
Successfully converted XML to JSON.'))
.catch(err => console.error('Conversion failed:', err));
How it works: This Node.js snippet demonstrates how to fetch XML data from an API and convert it into a JavaScript object (which behaves like JSON). It uses `axios` for HTTP requests (though a mock is used in the example for simplicity) and `xml2js` to parse the XML string. The `parseStringPromise` function, combined with options like `explicitArray: false` and `mergeAttrs: true`, helps produce a cleaner, more intuitive JSON structure by treating single elements as objects and merging attributes directly into the object's properties.