2 ways to Convert xml to JSON in Nodejs | Javascript


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

XML is extension markup language which contains properties or tags in the parent tag relation. JSOn is simple format to have a key and values pair enclosed in parenthiss{}.

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

You can check more about xml and json types This post talks about How to convert

Create a Nodejs Project

We are going to create a nodejs application creation from scratch.

Let’s create a nodejs application using npm init command

npm init or 
npm init -Y

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

How to Convert XML to JSON in Nodejs

There are many npm libraries which can use to parse xml and return json format.

  • xml2json
  • fast-xml-parser

using xml2json npm library

xml2json is a npm library used with limited functionality to parse xml file.

This parser does not parse the elements which has

  • CData sections
  • comments
  • Namespace preserve
  • attributes

Next, Install xml2json dependency to application using 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 JSON object

let’s declare xml file with 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 xml file and convert to JSON

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

Here is an example convert 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 JSON string. Here is synchronized version which runs the each line of code sequentially.

This has a drawback request has to wait a longer time when we have a large data setup like 1000MB of file sizes.

fs module readFileSync method which reads the sequentially and loads the data into memory before returning data to 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 feature

  • 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 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 parse method which accepts 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'
    }
  }

Sum up

To Sump Up, We have learned multiple ways to convert xml to json using npm library. xml2json is basic library with limited functionality, can be used for simple conversions and less size files, where as fast-xml-parser library is a robust with many more features. This can be used for validations and performance for bigger size of files.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.