Open In App

Convert xml data into json using Node.js

XML: Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity, generality, and usability across the Internet. It is a textual data format with strong support via Unicode for different human languages. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services.

Example:



<student>
    <details>
        <name> sravan</name>
        <id>1</id>
    </details>
    <details>
        <name> sudheer</name>
        <id>2</id>
    </details>
</student>

JSON: JSON stands for JavaScript Object Notation. It is a text-based data interchange format to maintain the structure of the data. JSON is the replacement of the XML data exchange format in JSON. It is easy to struct the data compare to XML. It supports data structures like arrays and objects and the JSON documents that are rapidly executed on the server. It is also a Language-Independent format that is derived from JavaScript. The official media type for the JSON is application/json and to save those file .json extension.

Example:



{"student":[
 { "Name":"sravan", "id":1 },
  { "Name":"sudheer", "id":2}
]}

Similarities:

Differences:

Approach:




// 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:


Article Tags :