🐍 How to Convert JSON to XML with Python: Complete Tutorial with Code Examples
Converting data between JSON and XML formats is a common task in web development, data integration, and API design.
Whether you're migrating legacy systems or building new applications, knowing how to perform this conversion efficiently in Python will save you a lot of time.
In this guide, we'll walk through everything you need — from basic examples to production-ready snippets.
🔍 What Are JSON and XML?
Before we dive into the code, let's clarify what these two formats represent.
- • JSON (JavaScript Object Notation)
A lightweight, human-readable format mainly used for APIs and web apps.
- • XML (Extensible Markup Language)
A markup-based format used widely in enterprise systems, configuration files, and legacy integrations.
Both formats structure data hierarchically, but they differ in syntax and metadata representation.
⚙️ Setup: Installing Required Libraries
Python doesn't include built-in XML–JSON conversion utilities, but you can install a lightweight package like xmltodict.
pip install xmltodictAlternatively, you can use dicttoxml if you only need JSON → XML conversion.
pip install dicttoxml🧩 Example 1: Convert JSON to XML Using xmltodict
Here's the most straightforward way to convert JSON to XML:
import json
import xmltodict
# Sample JSON string
json_data = '{"user": {"name": "Alice", "age": 25, "city": "Tokyo"}}'
# Convert JSON to Python dict
data_dict = json.loads(json_data)
# Convert dict to XML
xml_data = xmltodict.unparse(data_dict, pretty=True)
print(xml_data)Output:<?xml version="1.0" encoding="utf-8"?>
<user>
<name>Alice</name>
<age>25</age>
<city>Tokyo</city>
</user>💡 Tip:
You can set custom root tags or omit XML headers using parameters like:
xmltodict.unparse(data_dict, full_document=False)🧠 Example 2: Convert JSON to XML Using dicttoxml
dicttoxml provides more control over attributes and type annotations.
import json
from dicttoxml import dicttoxml
json_data = '{"product": {"id": 101, "name": "Laptop", "price": 899.99}}'
data_dict = json.loads(json_data)
xml_data = dicttoxml(data_dict, custom_root='catalog', attr_type=False)
print(xml_data.decode())Output:<catalog>
<product>
<id>101</id>
<name>Laptop</name>
<price>899.99</price>
</product>
</catalog>🔄 Bonus: Convert XML Back to JSON
You can easily reverse the process:
import xmltodict
import json
xml_data = """
<user>
<name>Alice</name>
<age>25</age>
</user>
"""
data_dict = xmltodict.parse(xml_data)
json_output = json.dumps(data_dict, indent=4)
print(json_output)Result:{
"user": {
"name": "Alice",
"age": "25"
}
}🚀 Full Script Example
Here's a compact function you can reuse in your projects:
import json
import xmltodict
def json_to_xml(json_string: str, root_tag: str = None) -> str:
data = json.loads(json_string)
if root_tag:
data = {root_tag: data}
return xmltodict.unparse(data, pretty=True)
# Usage
sample_json = '{"device": {"id": 123, "status": "active"}}'
xml_result = json_to_xml(sample_json, root_tag="devices")
print(xml_result)🌐 Online Alternative: Convert Instantly
Don't want to write any code?
Try our free online converter instead — simply paste or upload your JSON and download clean XML instantly:
👉 Convert JSON to XML – Free Online Tool
- • ✅ 100% free and private
- • ⚡ Instant conversion
- • 📁 Supports upload and download
🏁 Conclusion
Converting JSON to XML in Python is simple with tools like xmltodict and dicttoxml.
Whether you're processing API data or exporting structured reports, these snippets will handle most use cases.
If you just need a quick conversion, head over to:
🔗 https://www.jsonwork.com/en/tools/converters/json-to-xml/
and try it online — no setup needed!
Written by JsonWork.com – the fastest way to convert JSON online.