2 ways to Convert XML to JSON in Nodejs | Javascript example

This tutorial explains how to convert XML to JSON In javascript and Nodejs Applications.

XML is an extensible ```markdown language that contains properties or tags in the parent tag relation. JSON is a simple format to have a key and values pair enclosed in parenthesis`.

Both are used to store different types of data, there is no manual conversion from one type to another in nodejs and javascript

You can check more about xml and json types This post talks about How to convert XML to JSON in NodeJS

Create a Nodejs Project

We are going to create a nodejs application creation from scratch. You can also check other posts on npm command deprecate option is deprecated Let’s create a nodejs application using the npm init command

npm init or
npm init -Y

Above command initialize and create a nodejs application default values This command creates a nodejs application with all default values

How to Convert XML to JSON in Nodejs

Many npm libraries can use to parse XML and return JSON format.

  • xml2json
  • fast-xml-parser

using xml2json npm library

xml2json is an npm library used with limited functionality to parse XML files.

This parser does not parse the elements which have

  • CData sections
  • comments
  • Namespace preserve
  • attributes

Next, Install the xml2json dependency to an application using the below command

npm install xml2json --save

This adds dependency in package.json as follows

{
  "name": "Nodejs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "xml2json": "^0.12.0"
  }
}

Let’s write a code to parse XML to a JSON object

let’s declare an XML file with the below content

user.xml:

<users>
<user id="u12">
     <id>12</id>
     <username>john</username>
     <role>admin</role>
     <active>false</active>
     <create_date>2000-10-01</create_date>
</user>
</users>

Here are steps to read the XML file and convert it to JSON

  • Include the xml2json module using the require keyword which returns an object
  • We have to read a file from the file system, So fs module is an inbuilt module from Nodejs, have to include using require
  • Read the file with readFile from the fs module into the memory
  • readFile accepts filepath, encoding and callback function an
  • callback function is called with data and an error.
  • This asynchronously read the file data and gets the object into the data variable
  • xml2json module has toJson method which reads the XML and returns JSON Data

Here is an example of converting XML to JSON asynchronous parseXmlAsJsonAsync.js:

let xmlParser = require("xml2json");
let fs = require("fs");

fs.readFile("user.xml", "utf8", function (err, data) {
  if (err) {
    console.error(err);
    return;
  }
  let jsonData = xmlParser.toJson(data);
  console.log(jsonData);
});

Executing parseXmlAsJsonAsync.js returns the XML file content into a JSON string. Here is the synchronized version that runs each line of code sequentially.

It has a drawback request has to wait a long time when we have a large data set up like 1000MB of file sizes.

fs module readFileSync method reads the sequentially and loads the data into memory before returning data to the user.

parseXmlAsJsonsync.js:

let xmlParser = require("xml2json");
let fs = require("fs");

try {
  const xmlData = fs.readFileSync("user.xml", "utf8");
  let jsonData = xmlParser.toJson(xmlData);
  console.log(jsonData);
} catch (err) {
  console.error(err);
}

Fast xml parser

fast-xml-parser🔗 is robust library for XML content manipulation with many more features.

It has many features

  • Validate XML
  • Convert XML to/from javascript and JSON
  • Handling big files is good in terms of performance
  • Parse CData sections
  • support default all types including boolean
  • parse attributes and comments
  • It provides npm as well as CLI for
npm install fast-xml-parser

You can install using package.json using the npm install command

{
  "name": "Nodejs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "fast-xml-parser": "^3.19.0"
  }
}

Here is an example using fast-xml-parser It has a parse method that accepts the following parameters

It has three arguments

  • XML data
  • options default configurations can be passed
  • true - enable or disable internal XML validations
let xmlParser = require("xml2json");
var parser = require("fast-xml-parser");

let fs = require("fs");

fs.readFile("user.xml", "utf8", function (err, data) {
  if (err) throw err;
  var jsonData = parser.parse(data, null, true);

  console.log(jsonData);
});

Output:

{
users: {
user: {
id: 12,
username: 'john',
role: 'admin',
active: false,
create_date: '2000-10-01'
}
}

To Sum Up, We have learned multiple ways to convert XML to JSON using the npm library. xml2json is the basic library with limited functionality, and can be used for simple conversions and fewer size files, whereas the fast-xml-parser library is robust with many more features. This can be used for validations and performance for bigger size of files.