# How to convert XML to JSON in Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Apr 15, 2020, updated Oct 1, 2022. Topics: Node.js, JSON, XML.
Canonical URL: https://attacomsian.com/blog/nodejs-convert-xml-to-json

> A step-by-step guide to learn how to convert an XML file or a string to a JSON object by using Node.js.

In an [earlier article](https://attacomsian.com/blog/nodejs-convert-json-to-csv), 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](https://www.npmjs.com/package/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:

```bash
$ npm init -y
```

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

```bash
$ 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:

```bash
$ 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:

<p class="file-desc"><span>app.js</span></p>

```javascript
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()](https://attacomsian.com/blog/json-parse-stringify#jsonstringify) method.

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

```bash
$ node app.js
```

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

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

The `xml2js` package provides [several options](https://www.npmjs.com/package/xml2js#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:

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

Here is how the JSON output looks now:

```json
{
    "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:

```javascript
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](https://attacomsian.com/blog/nodejs-write-json-object-to-file) 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:

<p class="file-desc"><span>app-file.js</span></p>

```javascript
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](https://attacomsian.com/blog/reading-writing-files-nodejs) to learn more about reading and writing files in a Node.js application.

### JavaScript Promises

Want to use [promises](https://attacomsian.com/blog/promises-javascript) instead of the callback? The `xml2js` module provides a special method called `parseStringPromise()` that returns a promise as shown below:

<p class="file-desc"><span>app-promise.js</span></p>

```javascript
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](https://attacomsian.com/blog/async-await-javascript) syntax as shown in the following example:

<p class="file-desc"><span>app-async.js</span></p>

```javascript
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](https://github.com/attacomsian/code-examples/tree/master/nodejs/xml-to-json) 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](https://www.npmjs.com/package/xml2js) to learn about all the available methods and properties.

**Read Next:** [How to edit an XML file with Node.js](https://attacomsian.com/blog/nodjs-edit-xml-file)
