A
JSON file is a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which is a standard data interchange format. It is primarily used for transmitting data between a web application and a server.A
JSON object contains data in the form of a key/value pair. The keys are strings and the values are the JSON types. Keys and values are separated by a colon. Each entry (key/value pair) is separated by a comma. JSON files are lightweight, text-based, human-readable, and can be edited using a text editor.
Note: For more information, refer to
Working With JSON Data in Python
XML is a markup language which is designed to store data. It is case sensitive. XML offers you to define markup elements and generate customized markup language. The basic unit in the XML is known as an element. The XML language has no predefined tags. It simplifies data sharing, data transport, platform changes, data availability Extension of an XML file is .xml
Note: For more information, refer to
XML | Basics
Both JSON and XML file format are used for transferring data between client and server.
However, they both serve the same purpose though differ in their on way.
Comparison between JSON and XML
JSON |
XML |
JSON object has a type |
XML data is typeless |
JSON types: string, number, array, Boolean |
All XML data should be string |
Data is readily accessible as JSON objects |
XML data needs to be parsed |
JSON is supported by most browsers |
Cross-browser XML parsing can be tricky |
JSON has no display capabilities |
XML offers the capability to display data because it is a markup language |
JSON supports only text and number data type. |
XML support various data types such as number, text, images, charts, graphs, etc. It also provides options for transferring the structure or format of the data with actual data. |
Retrieving value is easy |
Retrieving value is difficult |
Supported by many Ajax toolkit |
Not fully supported by Ajax toolkit |
A fully automated way of deserializing/serializing JavaScript |
Developers have to write JavaScript code to serialize/de-serialize from XML |
Native support for object |
The object has to be express by conventions - mostly missed use of attributes and elements. |
It supports only UTF-8 encoding. |
It supports various encoding |
It doesn't support comments. |
It supports comments. |
JSON files are easy to read as compared to XML. |
XML documents are relatively more difficult to read and interpret. |
It does not provide any support for namespaces |
It supports namespaces. |
It is less secured. |
It is more secure than JSON. |
Handling JSON in Python 3
To handle the JSON file format, Python provides a module named
json
.
STEP 1: import the json module
import json as JS
STEP 2: import xml.etree.ElementTree module
import xml.etree.ElementTree as ET
STEP 3: Read the json file
here,
"data" is the variable in which we have loaded our JSON data.
with open("quiz.json", "r") as json_file:
data = JS.load(json_file);
STEP 4: Build the root element
Every xml file must have exactly one root element
root = ET.Element("quiz")
STEP 5: Build the subelements of the root
SubElement takes two parameters:
- root- It is the name of the variable where root element is stored.
- subelement_name: It is the name of subelement.Example:
Maths = ET.SubElement(root, "maths")
STEP 6: Build the tree of xml document
tree = ET.ElementTree(root)
STEP 7: Write the xml to quiz.xml file
tree.write("quiz.xml")
Note : XML elements does not support integer values so we need to convert them to string.
Example:
JSON File:
Python3 1==
# Program to read JSON file
# and generate its XML file
# Importing json module and xml
# module provided by python
import json as JS
import xml.etree.ElementTree as ET
# Opening JSON file in read mode
with open("myfile3.json", "r") as json_file:
# loading json file data
# to variable data
data = JS.load(json_file);
# Building the root element
# of the xml file
root = ET.Element("quiz")
# Building the sub root elements
# We don't add text since the value
# associated with subelement is a
# python dictionary
Maths = ET.SubElement(root, "maths")
# Building subelement of maths as q1
Q1 = ET.SubElement(Maths, "q1")
ET.SubElement(Q1, "question").
text = data["quiz"]["maths"]["q1"]["question"]
# Building multiple subelements with name options to hold different values
# Xml elements cannot hold integer values so we need to
# convert them to string
ET.SubElement(Q1, "options").text = str(data["quiz"]
["maths"]["q1"]
["options"][0])
ET.SubElement(Q1, "options").text = str(data["quiz"]
["maths"]["q1"]
["options"][1])
ET.SubElement(Q1, "options").text = str(data["quiz"]
["maths"]["q1"]
["options"][2])
ET.SubElement(Q1, "options").text = str(data["quiz"]
["maths"]["q1"]
["options"][3])
ET.SubElement(Q1, "answer").text = str(data["quiz"]
["maths"]["q1"]
["answer"])
# Building subelement of maths as q2
Q2 = ET.SubElement(Maths, "q2")
ET.SubElement(Q2, "question").text = data["quiz"]
["maths"]["q2"]["question"]
# Building multiple subelements
# with name options to hold
# different values
ET.SubElement(Q2, "options").text = str(data["quiz"]
["maths"]
["q2"]
["options"][0])
ET.SubElement(Q2, "options").text = str(data["quiz"]
["maths"]
["q2"]
["options"][1])
ET.SubElement(Q2, "options").text = str(data["quiz"]
["maths"]["q2"]
["options"][2])
ET.SubElement(Q2, "options").text = str(data["quiz"]
["maths"]["q2"]
["options"][3])
ET.SubElement(Q2, "answer").text = str(data["quiz"]
["maths"]["q2"]
["answer"])
# Building the tree of the xml
# elements using the root element
tree = ET.ElementTree(root)
# Writing the xml to output file
tree.write("quiz.xml")
Output:
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read