Converting XML data to JSON format is essential when integrating legacy XML feeds with modern web applications and APIs.
Python offers streamlined methods using high-level libraries like Pandas (`read_xml()` + `to_json()`) or standard library modules like ElementTree and json.
Consider the following sample XML file, data.xml, containing structured records:
<data>
<record>
<id>1</id>
<name>John Doe</name>
<age>30</age>
<city>New York</city>
</record>
<record>
<id>2</id>
<name>Jane Smith</name>
<age>25</age>
<city>Los Angeles</city>
</record>
<record>
<id>3</id>
<name>Emily Davis</name>
<age>35</age>
<city>Chicago</city>
</record>
</data>
The Pandas library provides the read_xml() method to parse XML data into a DataFrame effortlessly, which can then be exported as a JSON file using to_json().
import pandas as pd
# Input and output file paths
input_file = 'data.xml'
output_file = 'data.json'
# Read the XML file into a Pandas DataFrame
df = pd.read_xml(input_file)
# Export the DataFrame to a JSON file
df.to_json(output_file, orient='records', indent=4)
# Output confirmation
print(f"Data exported to {output_file} successfully.")
The ElementTree module, part of Python’s standard library, allows you to parse XML files iteratively and serialize data using the built-in json module.
import xml.etree.ElementTree as ET
import json
# Input and output file paths
input_file = 'data.xml'
output_file = 'data.json'
# Parse the XML file
tree = ET.parse(input_file)
root = tree.getroot()
# Extract data from XML
records = []
# Iterate through records
for record in root.findall('record'):
data = {}
for element in record:
data[element.tag] = element.text
records.append(data)
# Write data to JSON
with open(output_file, 'w', encoding='utf-8') as json_file:
json.dump(records, json_file, indent=4)
print(f"Data exported to {output_file} successfully.")
<record> elements within the XML document.| Feature | Pandas `read_xml()` | ElementTree + JSON |
|---|---|---|
| Ease of Use | Very simple and concise | Requires manual element iteration |
| Dependencies | Requires Pandas | Built into Python standard library |
| Customization | Limited parsing options | Full programmatic control over structure |
| Performance | Fast for flat, tabular XML | Better for deeply nested custom schemas |
Use Pandas `read_xml()` when working on data science pipelines where Pandas is already imported and the XML structure is relatively flat.
Use ElementTree when building lightweight scripts that avoid heavy third-party dependencies or require custom data transformations during conversion.
Both methods are highly effective for converting XML to JSON in Python. Choose the approach that best fits your project environment and data complexity.
Data Import Export using Tkinter GUI and Pandas DataFrame
Practice converting XML to JSON in our companion Jupyter Notebook:
Explore interactive code cells and test converting XML files to JSON using both Pandas and ElementTree.
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.