×

Convert XML to JSON in Python

XML conversion is very useful if we work on an API that returns data in JSON format and the source of data is in XML format.

JSON

A JSON file reserves the simple data structures and objects in JSON format, Json is a standard data exchange format. Json is used for data transmission among a server and web application.

The data in JSON object is in the form of a key and value pair. The keys refer to strings and the values are JSON types and these both are separated by a colon. By using the text editor Json files can be edited.

XML

XML is used for storing the data. It is case-sensitive. The markup items are defined with XML and produce personalized markup language. An element is defined as the basic unit. There is no predefined tags in XML. It clarifies sharing of data, transport of data, changes in the platform. 

Converting XML to JSON

There is no built-in library included in Python for working with XML. But we can do this using the xmltodict library and can be installed via PIP. First, we need to install xmltodict module via PIP

pip install xmltodict

Now, we need to import the inbulit module JSON by using the import keyword

import json

Reading the XML file

We can easily read the XML file with below code snippet

with open("xml_file.xml") as xml_file:

    data_dict = xmltodict.parse(xml_file.read())

Closing the XML file

xml_file.close()

Convert the xml_data into a dictionary

json_data = json.dumps(data_dict)

Writing the json_data to the output file

with open("data.json", "w") as json_file:

        json_file.write(json_data)

Closing the output file

json_file.close()

Example:

import xmltodict

import json

    obj = xmltodict.parse("""<teachers>

    <teacher memberid = "10001">

    <name> Akash mishra </name>

    <gender> male </gender>

    <subjects>

    <subject name= "Math" class= "KG" />

    <subject name= "Science" class= "PG" />

    <subject name= "Social Science" class = "LKG" />

    </subjects>

    </teacher>

    <teacher memberid = "10002">

    <name> Anuj rana </name>

    <gender> male </gender>

    <subjects>

    <subject name= "Math" class= "KG" />

    <subject name= "Science" class= "PG" />

    <subject name= "Social Science" class = "LKG" />

    </subjects>

    </teacher>

    </teachers>""")

    print(json.dumps(obj))

Output:

{"teachers": {"teacher": [{"@memberid": "10001", "name": "Akash mishra", "gender": "male", "subjects": {"subject": [{"@name": "Math", "@class": "KG"}, {"@name": "Science", "@class": "PG"}, {"@name": "Social Science", "@class": "LKG"}]}}, {"@memberid": "10002", "name": "Anuj rana", "gender": "male", "subjects": {"subject": [{"@name": "Math", "@class": "KG"}, {"@name": "Science", "@class": "PG"}, {"@name": "Social Science", "@class": "LKG"}]}}]}}

The xmltodict.parse() method is used for converting the XML document to a Python object.

Convert XML to Python Object

There is another library named untangle that is used for converting XML.

We can install it by using the below command

pip install untangle

Example:

import untangle

obj = untangle.parse("""

    <employees>

<employee>

   <name>Akash Sharma</name>

            <role>Software engineer</role>

            <age>29</age>

        </employee>

    </employees>

""")

#Access the name

print(obj.employees.employee.name.cdata)

Output:

Akash Sharma

Reading with untangle.parse method

import untangle

obj = untangle.parse("Employee.xml")

print(obj.employees.employee.name.cdata)

Output:

Akash Sharma

XML to JSON with Pandas

We can also convert XML to JSON with Pandas module. Pandas are essentially used for data cleaning in data science.

Installation

If we want to read XML with Pandas we need to install the pandas-read-xml via PIP. It can be installed by using the below command.

pip install pandas-read-xml

With using the below code we can conver XML to JSON in Pandas

import pandas_read_xml as pdx

df = pdx.read_xml("Student.xml")

print(df.to_json())

The Pandas module requires other modules for working(idna, numpy, chardet, pytz, six, python-dateutil, pandas, certifi, urllib3, requests, pyarrow). Because of this, it takes much memory so, the xmltodict method is highly efficient for XML to JSON conversion.

XML to JSON with Beautifulsoup

The main purpose of the Beautifulsoup library is parsing the HTML.It can also parse XML using the third-party parser known as lxml.Firstly, we need to install both modules.These can be easily installed with the below command

pip install beautifulsoup4

pip install lxml

Example:

from bs4 import BeautifulSoup

import json

#Loading xml

xml_parser = BeautifulSoup(open('Employee.xml'), 'xml')

Extracting the suitable information

name = xml_parser.find('name').contents[0]

age = xml_parser.find('age').contents[0]

role = xml_parser.find('role').contents[0]

employee = {

    'name':name,

    'age': age,

    'role': role

}

print(json.dumps(employee))

Output:

{"name": "Akash", "age": "29", "role": "Software engineer"}

Conclusion

In the above tutorial, you have understood how to convert the XML to JSON with different methods. We have seen different methods in the conversion of XML to JSON.


Related Topics

Python Program for Tower of Hanoi

In this tutorial, we will examine and learn about the Python coding used to create the video game Tower of Hanoi. Before seeing the game's step-by-step implementation in Python, we...

3 minutes read.

Python Glob

Methods for matching files that include particular patterns in accordance with UNIX shell-related expansion rules are referred to as "glob" methods. Similar methods for finding, locating, and searching for all of...

12 minutes read.

Multiprocessing in python

The word multiprocessing is used to compute the operation in which more than two processors run simultaneously with more than one central processor. The computer's performance increases gradually. Multiprocessing is...

6 minutes read.

Python Boolean

In this article, you will learn the boolean variables in python, bool() function in python, and bool operators with examples, Boolean Objects in Python. There are the only two possible values...

6 minutes read.

ComboBox in Python

Python includes several graphical user interface (GUI) libraries, including PyQT, Tkinter, Kivy, WxPython, and PySide. Tkinter is the most commonly used GUI module in Python because it is simple and...

2 minutes read.

Python program to find Fibonacci series

Python program to find Fibonacci series A Fibonacci series is an integer sequence of 0, 1, 1, 2, 3, 5, 8.... We can identify the Fibonacci series as any number sequence...

2 minutes read.

Python Set remove() method

Python Set remove() method The set.remove() method in Python removes the specified element from the set if it is present in the set else this method will raise an error if the specified item does...

2 minutes read.

Reverse a Number in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

Anytree Python

Python's anytree module is frequently used within data science-related software. Anytree has a Tolerant License, a Construct File that is public, no errors, no risks, and excellent support. One may...

3 minutes read.

Python round() function

Python round() function The round() function in Python returns a number rounded to ‘ndigits’ precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. Syntax round(number[, ndigits]) Parameter Number: This parameter represents the...

1 minute read.

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

Flutter Python

The flutter is a frame work available in the python programming language, to create web applications, mobile apps. The flutter is generally used for the development of the backend of...

3 minutes read.

Python program to find the area of a circle

Python program to find the area of a circle This article will discuss how to find the area of a circle in Python with a given radius. The area of a...

2 minutes read.

Python Program to Find the gcd of Two Numbers

Introduction Greatest Common Divisor is the full form of gcd. The greatest common divisor, or GCD, of two numbers, is a value that can exactly divide the two digits and is...

5 minutes read.

App Config Python

An XML file called App. Config serves as the document for any programme. In other terms, you can modify any configuration inside of it without going to edit the code...

7 minutes read.

How to Define a Function in Python?

What is a Function? In programming, a piece of code that executes a specific task or a group of related operations is known as a function. What does Python Functions Do? If you...

6 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python map() function

Python map() function The map() function in Python returns an iterator that applies a function to every item of iterable, yielding the results. Syntax map(function, iterable, ...) Parameter function: It is a required parameter that represents the function to...

1 minute read.

Python callable() Function

Python callable() Function The callable() function returns a boolean value ‘True’ if the specified object is callable, else it returns False. Syntax callable(object) Parameter Object:  The object parameter represents the value to test if it is callable...

1 minute read.

Why learn Python?

All things considered, learning python would be extraordinary, it'll acquaint you with the universe of dynamic programming dialects, if you're somebody who has had a semester of involvement with C. Python...

4 minutes read.