Home » Convert XML to JSON in Node
Convert XML to JSON in Node

Convert XML to JSON in Node


In the world of web development, data interchange formats play a crucial role in facilitating communication between different systems. Two widely used formats for this purpose are XML (Extensible Markup Language) and JSON (JavaScript Object Notation). While XML has been a longstanding choice for structuring data, JSON has gained popularity for its simplicity and ease of use. In this guide, we will explore the process of convert XML to JSON in a Node.js environment.

XML (Extensible Markup Language) and JSON (JavaScript Object Notation) are both widely used formats for representing and transmitting structured data. Here’s a brief overview of each:

XML (Extensible Markup Language):

  • XML is a markup language that is designed to store and transport data.
  • It uses tags to define the meaning and structure of the data, similar to HTML.
  • XML is often used for representing documents with a hierarchical structure and for exchanging data between different systems.
  • It is human-readable and can be easily parsed and processed by various programming languages.

Example of XML:

  <book category="fiction">
    <title>Harry Potter</title>
    <author>J.K. Rowling</author>
  <book category="non-fiction">
    <title>Thinking, Fast and Slow</title>
    <author>Daniel Kahneman</author>

JSON (JavaScript Object Notation):

  • JSON is a lightweight data interchange format derived from JavaScript.
  • It uses key-value pairs and arrays to represent data in a structured format.
  • JSON is commonly used for transmitting data between a web server and a client, and it is often used as a data format for web APIs.
  • It is easy for both humans and machines to read and write, and it is supported by many programming languages.

Example of JSON:

  "bookstore": {
    "books": [
        "category": "fiction",
        "title": "Harry Potter",
        "author": "J.K. Rowling"
        "category": "non-fiction",
        "title": "Thinking, Fast and Slow",
        "author": "Daniel Kahneman"

XML and JSON are both used for representing structured data, but they have different syntax and use cases. XML is often used for documents and data exchange, while JSON is commonly used for web APIs and data interchange between web servers and clients.

Why Convert XML to JSON?

Before diving into the conversion process, let’s briefly discuss why one might need to convert data from XML to JSON. JSON is a lightweight data interchange format that is easier for humans to read and write than XML. It is also more compact, making it an efficient choice for data transmission. Many modern web APIs and JavaScript-based applications prefer JSON as their data format. Therefore, converting XML to JSON can enhance interoperability and simplify data handling in a Node.js environment.

Step 1: Set Up Your Node.js Project

The first step is to set up a Node.js project if you don’t already have one. Navigate to your desired project directory and run the following commands in your terminal:

mkdir xml-to-json-converter
cd xml-to-json-converter
npm init -y

This will create a new Node.js project with a default package.json file.

Step 2: Install Dependencies

To convert XML to JSON in Node.js, we’ll use the xml2js library, a popular choice for parsing XML data. Install it by running:

npm install xml2js

This library provides a simple API for converting XML to JSON and vice versa.

Step 3: Create the XML File

For demonstration purposes, let’s create a sample XML file (data.xml) in your project directory:

<?xml version="1.0" encoding="UTF-8"?>
    <title>Node.js Guide</title>
    <author>John Doe</author>
    <title>Web Development Basics</title>
    <author>Jane Smith</author>

Step 4: Create the Node.js Script

Now, create a new file (e.g., convert.js) in your project directory and write the following code:

const fs = require('fs');
const xml2js = require('xml2js');

// Read XML file
const xmlData = fs.readFileSync('data.xml', 'utf-8');

// Parse XML to JSON
xml2js.parseString(xmlData, (err, jsonData) => {
  if (err) {
    console.error('Error parsing XML:', err);
  } else {
    // Convert JSON to a string with proper indentation
    const jsonString = JSON.stringify(jsonData, null, 2);

    // Write JSON to a file
    fs.writeFileSync('data.json', jsonString);
    console.log('Conversion successful! Check data.json');

Step 5: Run the Script

Execute the script by running:

node convert.js

This will read the XML data, convert it to JSON, and write the result to a new file (data.json). You can now inspect the converted JSON data.



In this guide, we’ve walked through the process of converting XML to JSON in a Node.js environment. We set up a Node.js project, installed the necessary dependencies, created a sample XML file, and wrote a simple script using the xml2js library to perform the conversion. This ability to seamlessly convert between XML and JSON is valuable for developers working with multiple data formats in web development projects.

Remember, understanding the intricacies of your data and the requirements of your application is crucial when choosing between XML and JSON. While JSON is often favored for its simplicity, XML continues to be relevant in certain scenarios. As you navigate the world of data interchange, having the skills to convert between these formats will undoubtedly prove beneficial in your journey as a web developer.

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *