Convert XML data into JSON using Node.js
Last Updated :
16 Oct, 2024
Improve
Converting XML data to JSON in Node.js is a common task, especially when working with APIs or services that return data in XML format. This conversion allows you to manipulate the data more easily using JavaScript objects.
Approach
To convert XML to JSON in Node we will use libraries like xml2js. First, parse the XML string, then transform it into JSON format, enabling easier manipulation of the data.
Steps to Convert XML data to JSON using Node
Step 1: Install Modules:
npm install xml2js
The updated dependencies in the package.json file will be:
"dependencies": {
"xml2js": "^0.4.23",
}
Step 2: We need to import xml2js and fs module.
- xml2js used to convert XML to JSON
- fs stands for file system which is used to locate our local file system
import { parseString } from "xml2js";
Step 3: String the results using JSON.stringify() method. Syntax:
JSON.stringify(results)
Example: This example converts the xml input data to json data using xml2js module.
// Filename - app.js
// import File System Module
import fs from "fs";
// import xml2js Module
import { parseString } from "xml2js";
//xml data
var xmldata = '<?xml version=”1.0" encoding=”UTF-8"?>' +
'<Student>' +
'<PersonalInformation>' +
'<FirstName>Sravan</FirstName>' +
'<LastName>Kumar</LastName>' +
'<Gender>Male</Gender>' +
'</PersonalInformation>' +
'<PersonalInformation>' +
'<FirstName>Sudheer</FirstName>' +
'<LastName>Bandlamudi</LastName>' +
'<Gender>Male</Gender>' +
'</PersonalInformation>' +
'</Student>';
// parsing xml data
parseString(xmldata, function (err, results) {
// parsing to json
let data = JSON.stringify(results)
// display the json data
console.log("results",data);
});
node code1.js
Output: