Converting XML to JSON using Node.js

Hi, Muggles

Today we are going to learn how to parse XML files into JSON using Node.js and express.

we need to install module using npm install — save xml-js

here we are using a small block of code to convert XML to JSON.

var convert = require(“xml-js”);

var xml = require(“fs”).readFileSync(path);

var xmlData = convert.xml2json(xml, {

compact: true,

spaces: 4


console.log(“converted json data “)

code explanation -:

At first, we are requiring xml-js module

then we are reading XML files using the fs.readFileSync method.

now we are using xml2json() function which is provided by xml-js API.

finally storing data in XML data variable and printing it.

more info about XML-js :

This library provides 4 functions: js2xml(), json2xml(), xml2js(), and xml2json().

var convert = require(‘xml-js’);

result = convert.js2xml(js, options); // to convert javascript object to xml text

result = convert.json2xml(json, options); // to convert json text to xml text

result = convert.xml2js(xml, options); // to convert xml text to javascript object

result = convert.xml2json(xml, options); // to convert xml text to json text

This is the code for converting an XML string into a JSON object.

This works for most cases. You can modify this code according to your own needs or requirements.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store