Convert json to xml using python

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

  1. a string
  2. json file
  3. API whose response is JSON.

Json

JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting data. It is often used when data is sent from a server to a web page. JSON is “self-describing” and easy to understand.

JSON data is written as name/value pairs, just like JavaScript object properties. JSON objects are written inside curly braces.

This is how a basic json looks like,

json

XML

XML stands for eXtensible Markup Language. XML was designed to store and transport data. XML was designed to be both human- and machine-readable.

xml

Now that we know the structure and what basically these two formats are we can install the python library and start right away!

Installation

The package can be installed using pip as,

pip install json2xml

From string

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,

xml data generated from json string

if we do not want the type in our output, we have to add one more attribute to the function “Json2xml”.

attr_type=False

change the last line like this,

print(json2xml.Json2xml(data, attr_type=False).to_xml())

This will remove the type in our xml output and we get a cleaner output like this.

xml output without the type attribute

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.

xml from a json file

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,

json

And the corresponding xml output from the code is,

xml response

Thanks for reading. This library will come in handy if you are working with APIs where you need different formats of response data.

Happy coding!