Python Convert JSON to XML

1. Introduction

In data processing and web services, JSON and XML are two widely used formats. While JSON is known for its simplicity and speed, XML is noted for its extensive feature set and wide support in enterprise systems. Converting JSON to XML can be necessary when interfacing with systems that require XML over JSON. This blog post will cover the steps needed to convert JSON data to XML format in Python.

Definition

JSON to XML conversion involves transforming the hierarchical structure of JSON, which is based on key-value pairs and arrays, into the nested tag structure of XML. There isn't a built-in Python library that directly converts JSON to XML, but this functionality can be achieved using third-party libraries or by manually constructing the XML.

2. Program Steps

1. Import the json module and any third-party library that can handle the conversion (e.g., xmltodict).

2. Define a JSON string that you want to convert to XML.

3. Parse the JSON string into a Python dictionary using json.loads().

4. Use the third-party library or manual methods to convert the dictionary to an XML string.

5. Output the XML string.

3. Code Program

# Step 1: Import necessary modules
import json
import xmltodict

# Step 2: Define a JSON string
json_str = '{"note": {"to": "Tove", "from": "Jani", "heading": "Reminder", "body": "Don't forget me this weekend!"}}'

# Step 3: Parse the JSON string into a Python dictionary
json_data = json.loads(json_str)

# Step 4: Convert the Python dictionary to an XML string using xmltodict
xml_str = xmltodict.unparse(json_data, pretty=True)

# Step 5: Print the XML string
print(xml_str)

Output:

<?xml version="1.0" encoding="utf-8"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

Explanation:

1. The json module is used to parse JSON strings and xmltodict is a third-party library that can convert between XML and dictionary objects.

2. json_str contains the JSON data structure as a string.

3. json_data is the dictionary representation of json_str, obtained using json.loads().

4. xml_str is the XML formatted string generated by xmltodict.unparse(), which takes a Python dictionary and produces an equivalent XML string. The pretty=True argument is used to format the XML for readability.

5. The output displays xml_str, which is the XML representation of the original JSON data. The printout shows an XML with a declaration and formatted tags corresponding to the JSON structure.


Comments