In this guide, we'll explore how to convert XML data to JSON using the xml2js library in Node.js.
1. Install xml2js Library
First, you need to install the xml2js library. Open your xml to json nodejs terminal and run the following command:
bash
Copy code
npm install xml2js
This will add the library to your Node.js project.
2. Require the xml2js Library
In your Node.js script, require the xml2js library:
javascript
Copy code
const xml2js = require('xml2js');
3. Convert XML to JSON
Now, let's create a function that takes XML data as input and converts it to JSON. For demonstration purposes, we'll assume you have an XML string, but you can modify the input source as needed (file, API response, etc.).
javascript
Copy code
const convertXmlToJson = (xmlString) => {
let jsonData;
// Parse XML to JSON
xml2js.parseString(xmlString, { explicitArray: false }, (error, result) => {
if (error) {
throw error;
}
jsonData = result;
});
return jsonData;
};
4. Example Usage
Now, let's use the convertXmlToJson function with a sample XML string:
javascript
Copy code
const xmlString = `
<root>
<person>
<name>John Doe</name>
<age>30</age>
<city>New York</city>
</person>
<person>
<name>Jane Doe</name>
<age>25</age>
<city>Los Angeles</city>
</person>
</root>
`;
const jsonResult = convertXmlToJson(xmlString);
console.log(JSON.stringify(jsonResult, null, 2));
5. Handle Asynchronous Operations
Keep in mind that xml2js.parseString is an asynchronous function. If you're working with XML data from external sources, it's essential to handle the conversion asynchronously using Promises or callbacks.
javascript
Copy code
const convertXmlToJsonAsync = (xmlString) => {
return new Promise((resolve, reject) => {
xml2js.parseString(xmlString, { explicitArray: false }, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
};
// Example usage with async/await
(async () => {
const xmlString = `<root><name>John</name><age>25</age></root>`;
try {
const jsonResult = await convertXmlToJsonAsync(xmlString);
console.log(JSON.stringify(jsonResult, null, 2));
} catch (error) {
console.error('Error converting XML to JSON:', error);
}
})();
Conclusion
With the xml2js library in Node.js, converting XML to JSON becomes a straightforward task. Ensure you handle asynchronous operations correctly if working with external data sources. Feel free to adapt the code according to your specific needs and use cases.
Remember to check the official documentation for the latest updates and features of the xml2js library.