How to convert XML to JSON in Node.js

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.