Convert XML to JSON in Python

Convert XML to JSON in Python

Muhammad Waiz Khan Mar-21, 2021 Mar-14, 2021 Python Python XML Python JSON

In this tutorial, we will look into the method to convert XML to JSON in Python. The JSON format is simpler to read and write than XML format; its compact style and lightweight also improve system performance, especially in RESTful APIs. As JSON is better than XML in many aspects, it is used as a replacement to XML in many fields.

Now, suppose we have data saved in XML format, and we want to convert it to JSON format; we can convert the XML data to JSON in Python using the following method.

Convert XML to JSON in Python Using the xmltodict Module

In Python, we have the json.dumps(obj) method that takes data as obj argument and serializes it as the JSON formatted stream and returns the formatted data as output.

The obj argument can be a dictionary, string, list, or tuple, etc, the json.dumps() method converts the obj according to its datatype. Like if we need a JSON object, we will have to provide the input as a dictionary, as the json.dumps() method converts the dictionary to the JSON object. The list or tuple type is converted to JSON array and string type to JSON string.

We can use the xmltodict.parse() method to convert the XML data to the Python dictionary data type. The xmltodict.parse() method takes XML format data as a string, parses the data, and returns the output as a dictionary.

After converting the data to a dictionary using the xmltodict.parse() method, we can use the json.dumps() method to convert the data to the JSON object.

The below example code demonstrates how to convert the XML data to JSON using the json.dumps() and xmltodict.parse() method in Python.

import xmltodict
import json

dictionary = xmltodict.parse("""<note>
  <msg>Let's meet this weekend!</msg>
json_object = json.dumps(dictionary) 


{"note": {"date": "2021-03-07", "time": "15:23", "to": "Sara", "from": "Khan", "msg": "Let's meet this weekend!"}}

Related Article - Python XML

  • Convert XML to CSV Using Python
  • Pretty Print XML Output Pretty in Python
  • Create an XML Parser in Python
  • Convert XML to Dictionary in Python
  • Related Article - Python JSON

  • Get JSON From URL in Python
  • Pretty Print a JSON File in Python
  • Append Data to a JSON File Using Python
  • Flatten JSON in Python
  • Python Compare Multilevel JSON Objects Using JSON Diff
  • Serialize a Python Class Object to JSON