How to convert XML to JSON in Python
In this tutorial, we will learn how to convert XML data to JSON data and also to convert an XML file to JSON data in Python.
XML (Extensible Markup Language) is a markup language like HTML and used to store and transport data. On the other hand, JSON (JavaScript Object Notation) is a popular data format used for data manipulation. Usually, developers prefer JSON to XML. So we have to learn a way how to convert from XML to JSON. But the conversion will be easy if we convert XML to Python dictionary and then from Python dictionary to JSON.
Probably you are a student who needs coding assistance? Feel free to get Python online homework help at AssignmentCore whose experts will do a high-quality Python assignment for you.
Convert XML to JSON in Python
We can convert XML to the Python dictionary using the ‘xmltodict’ module. So, first of all, ‘xmltodict’ should be installed using the ‘pip‘ command from the command prompt like this.
pip install xmltodict
The screenshot of the result is given below.
Now in the python idle, we have to import ‘xmltodict’ and ‘json’ as shown below.
import xmltodict import json
Now to convert XML to a Python dictionary we use the ‘parse’ method of the ‘xmltodict’ module and to convert the Python dictionary to JSON we use the ‘dumps‘ method of the ‘json’ module. See the below code.
import xmltodict import json xml='''<website> <name>Codespeedy</name> <article>Related to programming</article> <message>You can learn easily from codespeedy</message> </website>''' my_dict=xmltodict.parse(xml) json_data=json.dumps(my_dict) print(json_data)
Output:
{"website": {"name": "Codespeedy", "article": "Related to programming", "message": "You can learn easily from codespeedy"}}
In the above code, the XML data ‘xml’ is converted into the dictionary ‘my_dict’ by the ‘parse’ method and ‘my_dict’ is converted into the JSON data json_data’ using the ‘dumps’ method’.
Convert XML file to JSON in Python
Let’s consider the following XML file saved as ‘my_xml. xml’.
<website> <name>Codespeedy</name> <article>Related to programming</article> <message>You can learn easily from codespeedy</message> </website>
Firstly, we should open the ‘.xml’ file using ‘open‘ function and then use ‘read()‘ function to read the file content. Now we can convert it into JSON in the same way we followed earlier.
import xmltodict import json with open('my_xml.xml') as xml_file: my_dict=xmltodict.parse(xml_file.read()) xml_file.close() json_data=json.dumps(my_dict) print(json_data)
Output:
{"website": {"name": "Codespeedy", "article": "Related to programming", "message": "You can learn easily from codespeedy"}}
You may also read:
- How To Convert Python Dictionary To JSON
- Convert JSON String To Python Dictionary
- How To Convert JSON To CSV in Python
I cannot believe I googled this issue and missed this post so many times and wasted so much time.
This is great, thank you.
simple and concise! the way I like it! Great job!