How to Convert XML to JSON in Python?

Estimated read time 1 min read

In Python, you can convert XML data to JSON format using the xmltodict module, which provides easy-to-use functions for parsing and manipulating XML data. Here’s an example:

import json
import xmltodict

# Load XML data
with open('example.xml') as xml_file:
    xml_data =

# Parse XML to dictionary
dict_data = xmltodict.parse(xml_data)

# Convert dictionary to JSON
json_data = json.dumps(dict_data)

# Write JSON data to file
with open('output.json', 'w') as json_file:

print("XML data converted to JSON successfully!")

In this example, the xml_file is read using the open() function, and its contents are stored in the xml_data variable. Then, the xmltodict.parse() function is used to parse the XML data into a Python dictionary dict_data. Next, the json.dumps() function is used to convert the dictionary to a JSON string json_data. Finally, the JSON data is written to a file named “output.json” using the open() function with write mode (“w”), and the converted JSON data is written to the file using the write() method.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply