In this article we shall how to convert json to xml. This can be done easily by using this library called “json2xml”. Using this library we can convert json data from
- a string
- json file
- API whose response is JSON.
This is how a basic json looks like,
XML stands for eXtensible Markup Language. XML was designed to store and transport data. XML was designed to be both human- and machine-readable.
Now that we know the structure and what basically these two formats are we can install the python library and start right away!
The package can be installed using pip as,
pip install json2xml
First let us see how to convert the json data in a string format to xml. Consider the following code snippet. The json string is passed to the “readfromstring” method.
The output of this code is an xml string which is,
if we do not want the type in our output, we have to add one more attribute to the function “Json2xml”.
change the last line like this,
This will remove the type in our xml output and we get a cleaner output like this.
From a json file
We can also convert the json data from a file directly to XML by using the “readfromjson” method. The example code looks like this.
The output is same as the above code as i have used the same json here also in the “user.json” file.
From a url
We can also generate xml from urls which returns a json response. I am using a random api from the internet which gives us a json response. The url is “http://api.plos.org/search?q=title:%22Drosophila%22%20and%20body:%22RNA%22&fl=id&start=1&rows=10“.
The code snippet looks like this.
The json response from the site is,
And the corresponding xml output from the code is,
Thanks for reading. This library will come in handy if you are working with APIs where you need different formats of response data.