Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Sat Apr 29 2023

How to parse XML data to JSON in NodeJs

In this tutorial, we will demonstrate how to parse XML data into a JSON object using the great library called fast-xml-parser. Link to the NPM package.

Our example XML that we will parse

Below is our XML that we should parse into a JSON object.

<items> <item id="0001" type="donut"> <name>Cake</name> <ppu>0.55</ppu> <batters> <batter id="1001">Regular</batter> <batter id="1002">Chocolate</batter> <batter id="1003">Blueberry</batter> </batters> <topping id="5001">None</topping> <topping id="5002">Glazed</topping> <topping id="5005">Sugar</topping> <topping id="5006">Sprinkles</topping> <topping id="5003">Chocolate</topping> <topping id="5004">Maple</topping> </item> </items>

Read local file

In our example, we will work with a local xml file. In a real world scenario, we probably would get the xml from a GET request or similar, nevertheless, the parsing will work the same.

This is how we read the file that we will parse

const fs = require("fs"); const xml = fs.readFileSync("./xmldata.xml", "utf8");

Parse to JSON

All right, now we will do some parsing.

const fs = require("fs"); const { XMLParser } = require("fast-xml-parser"); const xml = fs.readFileSync("./xmldata.xml", "utf8"); const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: "", }); console.log(JSON.stringify(parser.parse(xml)));

In above code, we are importing fast-xml-parser and creating an instance with some options.

  • ignoreAttributes will make sure we get all the attributes from the XML
  • attributeNamePrefix will not prefix the attributes. Per default, it will be prefixed with @_. So setting this to false, our JSON will keep the orignial attribute names.

Our result in JSON

And after parsing and logging the result, it will look like this in our JSON object

{ "items": { "item": { "name": "Cake", "ppu": 0.55, "batters": { "batter": [ { "#text": "Regular", "id": "1001" }, { "#text": "Chocolate", "id": "1002" }, { "#text": "Blueberry", "id": "1003" } ] }, "topping": [ { "#text": "None", "id": "5001" }, { "#text": "Glazed", "id": "5002" }, { "#text": "Sugar", "id": "5005" }, { "#text": "Sprinkles", "id": "5006" }, { "#text": "Chocolate", "id": "5003" }, { "#text": "Maple", "id": "5004" } ], "id": "0001", "type": "donut" } } }

And now a human being can do some actual work with the data :)

Outro

In this post, we learned how to parse XML to JSON by using a third-party lib called fast-xml-parser.

There are sometimes scenarios where we need to work with XML. I guess it is not that common anymore, but still, it occurs. Being able to transform it to JSON, which is much more easy to work with, is really handy. I hope you got something out of this post, and thanks for reading.

Have a great day!

signatureSat Apr 29 2023
See all our articles