Skip to content
Related Articles

Related Articles

Convert xml data into json using Node.js
  • Last Updated : 09 Apr, 2021

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:



  • JSON and XML are “self describing” nature
  • JSON and XML are hierarchical
  • We can parse JSON and XML
  • We can include XAML along with JSON and vive versa.

Differences:

  • JSON doesn’t use end tag whereas xml used end tag
  • JSON is shorter than xml
  • JSON is quicker to read and write
  • JSON can use arrays but xml can’t use arrays.

Approach:

  • We need to import xml2js and fs module.
    1. xml2js used to convert XML to JSON
    2. fs stands for file system which is used to locate our local file system
  • String the results using JSON.stringify() method.

    Syntax:

    JSON.stringify(results)
  • Install Modules:
    npm install fs xml2js

code1.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:

My Personal Notes arrow_drop_up
Recommended Articles
Page :