Convert XML to JSON using Python.
ExploreExchange IdeasEducational ProgramsEnhance SkillsUpgrade Article
Preserve Article
Favor Article
A JavaScript Object Notation (JSON) document corresponds to a JavaScript syntax-based file that securely stores basic data structures and objects. Essentially, it is a common framework for exchanging information between a web application and a server. A JSON entity embodies data in the form of a key-value pairing. The keys represent strings, and the values denote the unique data types within JSON. Separated by colons, each key-value entry is distinctly segregated by commas. For ease of editing, JSON files are lightweight, textual, and human-friendly, effortlessly modifiable through any text editor.
Remark: To acquire additional insights, kindly consult the resource on Handling JSON Data in Python.
Extensible Markup Language (XML) stands as a case-sensitive markup language that caters to the storage of diverse data. XML empowers users to customize and generate specific markup elements of their choice. The fundamental unit within XML manifests as an element. Unlike JSON, XML lacks predefined tags, leading to effortless data sharing, platform adjustments, and expansive data accessibility. XML files possess a .xml extension signifying their identity.
Remark: To gain additional insights and knowledge, kindly refer to the resource on XML | Fundamental Concepts.
Both JSON and XML formats are employed for efficient data transmission amidst clients and servers.
However, they seamlessly fulfill this purpose while diverging in their respective characteristics.
A Comparative Examination of JSON and XML
JSONXMLJSON data embodies distinct typesXML represents data in a typeless mannerJSON data types: string, number, array, BooleanXML necessitates all data to be in string formatJSON data is immediately accessible through objectsXML data necessitates parsingJSON boasts extensive browser supportCross-browser XML parsing often poses challengesJSON lacks display capabilitiesXML's functionality lies in its ability to display data alongside its markup propertiesJSON solely supports text and numerical data typesXML supports an array of data types, encompassing numerical values, textual information, images, charts, graphs, etc. Furthermore, XML facilitates data structure and format transfer along with the actual data retrieval.Retrieving values from JSON is straightforwardRetrieving values from XML proves challengingJSON enjoys widespread compatibility with numerous Ajax toolkitsAjax toolkit support for XML remains incompleteJSON seamlessly facilitates JavaScript's automatic deserialization/serializationXML requires developers to manually script JavaScript for serialization and deserializationJSON features native object supportXML object representation conventionally relies on attributes and elementsJSON solely supports UTF-8 encodingXML supports multiple encoding optionsJSON lacks support for commentsXML fully incorporates comment utilizationJSON files offer enhanced readability in contrast to XMLXML documents present elevated complexity in terms of readability and interpretationJSON lacks built-in namespace supportXML comprehensively supports namespacesJSON possesses limited security measuresXML surpasses JSON in terms of security features.Converting XML to JSON
Method 1: Employing the xmltodict and json modules
To handle the JSON file format, Python provides the json module, ensuring seamless handling and processing.STEP 1: Start by installing the xmltodict module using pip or any other python package manager. Use the following command:
pip install xmltodict
STEP 2: Next, import the json module in your python code using the keyword "import".
import json
STEP 3: Now, let's read the xml file. In the code snippet below, the variable "data_dict" will contain the loaded XML data in the form of a dictionary datatype.

with open("xml_file.xml") as xml_file:
data_dict = xmltodict.parse(xml_file.read())
STEP 4: In this step, we will convert the xml data into a dictionary and store it in a variable. JSON objects are enclosed by curly braces { } and are written in key-value pairs. Here, we will utilize the following functions:
- json.loads() takes a string as input and returns a json object
- json.dumps() takes a json object as input and returns a string
Since we are using xml data as the input string and generating a python object, we will use json.dumps().
json_data = json.dumps(data_dict)
In the code snippet above, "json_data" is the variable used to store the generated object.
STEP 5: Finally, write the json data to an output file. Use the following code:
with open("data.json", "w") as json_file:
json_file.write(json_data)
Example:
XML File:
Converting XML to JSON using Python
Python3
import json
import xmltodict
with open("test.xml") as xml_file:
data_dict = xmltodict.parse(xml_file.read())

json_data = json.dumps(data_dict)
with open("data.json", "w") as json_file:
json_file.write(json_data)
Output:
xml to json
Method 2: Using the built-in Python module

XML File
Python3
import xml.etree.ElementTree as E
tree = E.parse('a.xml')
To begin, we need to get the root element of the tree using the "getroot()" function. Let's assign it to a variable called "root":
tree = get_tree()
root = tree.getroot()
Next, we will create an empty dictionary called "d":
d = {}
Now, we will iterate over each child element in the root element:
for child in root:
If the tag of the child element is not already in the dictionary "d", we will add it as a key with an empty list value:
if child.tag not in d:
d[child.tag] = []
Next, we will create an empty dictionary called "dic" to store the child elements of the current child element:
dic = {}
Now, we will iterate over each child2 element in the current child element:
for child2 in child:
If the tag of the child2 element is not already in the dictionary "dic", we will add it as a key with the text of the child2 element as its value:
if child2.tag not in dic:
dic[child2.tag] = child2.text
Finally, we will append the dictionary "dic" to the list associated with the tag of the current child element in the dictionary "d":
d[child.tag].append(dic)
Next, we will print the dictionary "d" to see the output:
print(d)
The expected output should be as follows:
{
'details': [
{
'firstname': 'Shiv',
'lastname': 'Mishra',
'title': 'Engineer',
'division': 'Computer',
'building': '301',
'room': '11'
},
{
'firstname': 'Yuh',
'lastname': 'Datta',
'title': 'Developer',
'division': 'Computer',
'building': '303',
'room': '02'
},
{
'firstname': 'Rahil',
'lastname': 'Khan',
'title': 'Tester',
'division': 'Computer',
'building': '304',
'room': '10'
},
{
'firstname': 'Deep',
'lastname': 'Parekh',
'title': 'Designer',
'division': 'Computer',
'building': '305',
'room': '14'
}
]
}

If you're thinking about taking a trip to the United States, you might consider exchanging some of your money into U.S. dollars, which is the official currency of the country. The international symbol for the currency is USD.USD is also the official currency in a few other countries, including Ecuador

If you're considering a journey to the United States, it might be beneficial to convert some of your money into U.S. dollars, which is the official currency of the country. The internationally recognized symbol for this currency is USD.Additionally, USD serves as the official currency in Ecuador and El

Utilize our inch-to-fraction calculator to effortlessly perform conversions between inch fractions, decimal values, metric measurements, and feet. Effective Techniques for Calculating Inch FractionsInches can be represented as fractions or decimals. When dealing with inch fractions, it is vital to

Please enter the necessary values below to convert kilowatts [kW] to British thermal units per hour [Btu/h], or the other way around.Description: A kilowatt (symbol: kW) is a unit of power within the International System of Units (SI). The watt, after the Scottish inventor James Watt, serves as the base