In an earlier article, I explained how to convert a JSON array into a CSV file in a Node.js application. Today, we'll look at how to parse an XML file or a string to a JSON object.

To perform the XML to JSON conversion, we'll be using the xml2js module from Node Package Manager (NPM). This package provides a convenient API that does all the heavy lifting for us.

Create an Application

Let us first create a new Node.js application and install all the required dependencies. Switch to the folder where you want to store your project files and run the following command in the terminal:

$ npm init -y

The above command will create a package.json file in the root directory. Next, install the only required dependency — xml2js by executing the following command:

$ npm install xml2js --save

This will create a node_modules directory inside your project containing all the dependencies required by the xml2js module.

Convert XML to JSON

To convert an XML string to a JSON object, first create a new JavaScript file named app.js in your project root directory:

$ touch app.js

If the touch command is unavailable, just create the file manually. Open the app.js file in your favorite editor and add the following code:

app.js

const xml2js = require('xml2js')

// XML string to be parsed to JSON
const xml = `<?xml version="1.0" encoding="UTF-8" ?>
            <user id="1">
                <name>John Doe</name>
                <email>john.doe@example.com</email>
                <roles>
                    <role>Member</role>
                    <role>Admin</role>
                </roles>
                <admin>true</admin>
            </user>`

// convert XML to JSON
xml2js.parseString(xml, (err, result) => {
  if (err) {
    throw err
  }

  // `result` is a JavaScript object
  // convert it to a JSON string
  const json = JSON.stringify(result, null, 4)

  // log JSON string
  console.log(json)
})

The above example code parses an XML string and converts it into a JavaScript object. To convert the JavaScript object into its JSON representation, we are using the JSON.stringify() method.

To see the output, type the following command to launch the Node.js application:

$ node app.js

If everything goes right, you should see the following JSON printed on the console:

{
    "user": {
        "$": {
            "id": "1"
        },
        "name": [
            "John Doe"
        ],
        "email": [
            "john.doe@example.com"
        ],
        "roles": [
            {
                "role": [
                    "Member",
                    "Admin"
                ]
            }
        ],
        "admin": [
            "true"
        ]
    }
}

The xml2js package provides several options that you can pass as a second argument to further customize the output. For example, you can set mergeAttrs: true to merge attributes and child elements as properties of the parent instead of keying attributes off a child attribute object:

xml2js.parseString(xml, { mergeAttrs: true }, (err, result) => {
  // ...
})

Here is how the JSON output looks now:

{
    "user": {
        "id": [
            "1"
        ],
        "name": [
            "John Doe"
        ],
       // ...
    }
}

As you can see above, id is now merged with the user object, and the special $ attribute is removed.

Write JSON to File

To write the output JSON string to a file for further processing, you can use the following JavaScript code:

xml2js.parseString(xml, { mergeAttrs: true }, (err, result) => {
  if (err) {
    throw err
  }

  // `result` is a JavaScript object
  // convert it to a JSON string
  const json = JSON.stringify(result, null, 4)

  // save JSON in a file
  fs.writeFileSync('user.json', json)
})

Read this guide to learn more about writing JSON to a file in Node.js.

Read XML from File

If your XML data is stored in a file, you can read it by using the native fs module and then perform the conversion as shown below:

app-file.js

const xml2js = require('xml2js')
const fs = require('fs')

// read XML from a file
const xml = fs.readFileSync('user.xml')

// convert XML to JSON
xml2js.parseString(xml, { mergeAttrs: true }, (err, result) => {
  if (err) {
    throw err
  }

  // `result` is a JavaScript object
  // convert it to a JSON string
  const json = JSON.stringify(result, null, 4)

  // save JSON in a file
  fs.writeFileSync('user.json', json)
})

Read this guide to learn more about reading and writing files in a Node.js application.

JavaScript Promises

Want to use promises instead of the callback? The xml2js module provides a special method called parseStringPromise() that returns a promise as shown below:

app-promise.js

const xml2js = require('xml2js')
const fs = require('fs')

// read XML from a file
const xml = fs.readFileSync('user.xml')

// convert XML to JSON
xml2js
  .parseStringPromise(xml, { mergeAttrs: true })
  .then(result => {
    // convert it to a JSON string
    const json = JSON.stringify(result, null, 4)

    // save JSON in a file
    fs.writeFileSync('user.json', json)
  })
  .catch(err => console.log(err))

Async-Await

The xml2js module also supports async-await syntax as shown in the following example:

app-async.js

const xml2js = require('xml2js')
const fs = require('fs')

// read XML from a file
const xml = fs.readFileSync('user.xml')

// convert XML to JSON
;(async () => {
  try {
    const result = await xml2js.parseStringPromise(xml, { mergeAttrs: true })

    // convert it to a JSON string
    const json = JSON.stringify(result, null, 4)

    // save JSON in a file
    fs.writeFileSync('user.json', json)
  } catch (err) {
    console.log(err)
  }
})()

Source Code: Download the complete source code from GitHub available under MIT license.

Conclusion

In this article, we looked at several examples to learn how to complete XML to JSON conversion in a Node.js application by using the xml2js package.

Read the xml2js module's documentation to learn about all the available methods and properties.

Read Next: How to edit an XML file with Node.js

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.