To handle the JSON file format, Python provides a module named json
.
STEP 1: install xmltodict module using pip or any other python package manager
pip install xmltodict
STEP 2: import json module using the keyword import
import json
STEP 3: Read the xml file
here, data_dict is the variable in which we have loaded our XML data after converting it to dictionary datatype.
with open("quiz.xml") as xml_file:
data_dict = xmltodict.parse(xml_file.read())
STEP 4: Close the XML file
xml_file.close()
STEP 5: Convert the xml_data into a dictionary and store it in a variable
JSON object are surrounded by curly braces { }. They are written in key and value pairs.
json.loads() takes in a string and returns a json object.
json.dumps() takes in a json object and returns a string.
We use xml_data as input string and generate pyhon object, so we use json.dumps()
json_data = json.dumps(data_dict)
Here, json_data is the variable used to store the generated object.
STEP 6: Write the json_data to output file
with open("text3.json", "w") as json_file:
json_file.write(json_data)
STEP 7: Close the output file
json_file.close()
Example:
XML File:
Python Program:
# Program to convert an xml
# file to json file
# import json module and xmltodict
# module provided by python
import json
import xmltodict
# open the input xml file and read
# data in form of python dictionary
# using xmltodict module
with open("quiz.xml") as xml_file:
data_dict = xmltodict.parse(xml_file.read())
xml_file.close()
# generate the object using json.dumps()
# corresponding to json data
json_data = json.dumps(data_dict)
# Write the json data to output
# json file
with open("text3.json", "w") as json_file:
json_file.write(json_data)
json_file.close()
output:
JSON file:
Comments