DEV Community

loading...

How can I convert data from XML to JSON format?

shubham2270 profile image Shubham Kumar ・1 min read

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.

Discussion (5)

pic
Editor guide
Collapse
kenbellows profile image
Ken Bellows

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
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
appdevtools profile image
AppDevTools

In case this can be useful for your testing and debugging purposes, feel free to use JSON / XML Converter to convert between JSON and XML data on the browser.

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...