Converting XML to JSON in Node.js

Converting XML to JSON in Node.jsConverting XML to JSON in Node.js

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
      nameJohn Doe/name
      age30/age
      cityNew York/city
    /person
    person
      nameJane Doe/name
      age25/age
      cityLos 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 = `rootnameJohn/nameage25/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.


alliance2233

176 Blog posts

Comments