DEV Community

Shubham Kumar
Shubham Kumar

Posted on

How can I convert data from XML to JSON format?

I am getting API data from somewhere but it is only providing the data in XML format so are there any way I can convert the XML data to JSON and use it as per my need? I will be using Javascript to develop a web app using that data.

Top comments (5)

Collapse
 
kenbellows profile image
Ken Bellows • Edited

Couple thoughts. First, you may not need to; JavaScript has solid native support for dealing with XML documents. If you want to check that out, start with this MDN article on dealing with XML in JavaScript.

But if you really need to translate to JSON (or just want to, because let's be real, JSON is way easier to work with than XML), then the question is how you want to do it. XML has an extra feature that JSON doesn't have: attributes. You have to decide how you want to distinguish between element contents and attributes when you convert to JSON.

David Walsh has an old blog post demonstrating his personal JavaScript function for converting XML to JSON. It uses a pretty popular method, which is to add a special property at each level that has attributes called "@attributes" and put the attribute values in there.

Collapse
 
murugan_s profile image
Murugan • Edited

Hi @kenbellows I have tried the xml to json conversion using DOM parser in nodejs. After parsing it I have tried to get the get the node using document.getElementsByTagName.
But this is not working when my tag name is not in small case.
For eg: if my tagname is "Userprofile"

Can you please help me with this?

Collapse
 
imkrunal profile image
Krunal Shah

I am working on events ticket projects and found myself in the same situation as yours. I found an npm package xml2js and it works quite well for me you can check it out npmjs.com/package/xml2js

Collapse
 
bias profile image
Tobias Nickel

I think you want the fastest parser with a clean API, that does not need meaningless callbacks like xml2js.

txml is definetly the fastest xml parser.

Collapse
 
mddanishyusuf profile image
Mohd Danish

Hey, you can give a try to this API. nocodeapi.com/docs/xml-to-json-noc...