The Wayback Machine - https://web.archive.org/web/20240916090834/https://www.geeksforgeeks.org/working-with-json-data-in-python/
Open In App

Working With JSON Data in Python

Last Updated : 03 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python. JSON shows an API similar to users of Standard Library marshal and pickle modules and Python natively supports JSON features. For example:  

Python3




# Python program showing
# use of json package
 
import json
 
# {key:value mapping}
a ={"name":"John",
   "age":31,
    "Salary":25000}
 
# conversion to JSON done by dumps() function
 b = json.dumps(a)
 
# printing the output
print(b)


Output: 

{"age": 31, "Salary": 25000, "name": "John"}

As you can see, JSON supports primitive types, like strings and numbers, as well as nested lists, tuples, and objects  

Python3




# Python program showing that
# json support different primitive
# types
 
import json
 
# list conversion to Array
print(json.dumps(['Welcome', "to", "GeeksforGeeks"]))
 
# tuple conversion to Array
print(json.dumps(("Welcome", "to", "GeeksforGeeks")))
 
# string conversion to String
print(json.dumps("Hi"))
 
# int conversion to Number
print(json.dumps(123))
 
# float conversion to Number
print(json.dumps(23.572))
 
# Boolean conversion to their respective values
print(json.dumps(True))
print(json.dumps(False))
 
# None value to null
print(json.dumps(None))


Output: 

["Welcome", "to", "GeeksforGeeks"]
["Welcome", "to", "GeeksforGeeks"]
"Hi"
123
23.572
true
false
null

Serializing JSON: 

The process of encoding JSON is usually called serialization. This term refers to the transformation of data into a series of bytes (hence serial) to be stored or transmitted across a network. To handle the data flow in a file, the JSON library in Python uses dump() function to convert the Python objects into their respective JSON object, so it makes it easy to write data to files. See the following table given below.  

Python object JSON object
dict object
list, tuple array
str string
int, long, float numbers
True true
False false
None null

Example: Serialization  

Consider the given example of a Python object.

Python3




var = {
      "Subjects": {
                  "Maths":85,
                  "Physics":90
                   }
      }


Using Python’s context manager, create a file named Sample.json and open it with write mode. 

Python3




with open("Sample.json", "w") as p:
     json.dump(var, p)


Here, the dump() takes two arguments first, the data object to be serialized, and second the object to which it will be written(Byte format). 

Deserializing JSON:

Deserialization is the opposite of Serialization, i.e. conversion of JSON objects into their respective Python objects. The load() method is used for it. If you have used JSON data from another program or obtained it as a string format of JSON, then it can easily be deserialized with load(), which is usually used to load from a string, otherwise, the root object is in a list or dict. 

Python3




with open("Sample.json", "r") as read_it:
     data = json.load(read_it)


Example: Deserialization 

Python3




json_var ="""
{
    "Country": {
        "name": "INDIA",
        "Languages_spoken": [
            {
                "names": ["Hindi", "English", "Bengali", "Telugu"]
            }
        ]
    }
}
"""
var = json.loads(json_var)


Encoding and Decoding: 

Encoding is defined as converting the text or values into an encrypted form that can only be used by the desired user through decoding it. Here encoding and decoding is done for JSON (object)format. Encoding is also known as Serialization and Decoding is known as Deserialization. Python has a popular package for this operation. This package is known as Demjson. To install it follow the steps below. 

For Windows: 

pip install demjson

For Ubuntu:

 sudo apt-get update
 sudo apt-get install python-demjson

Encoding: The encode() function is used to convert the python object into a JSON string representation.

Syntax:  

demjson.encode(self, obj, nest_level=0) 

Example 1: Encoding using demjson package. 

Python3




# storing marks of 3 subjects
var = [{"Math": 50, "physics":60, "Chemistry":70}]
print(demjson.encode(var))


Output: 

[{"Chemistry":70, "Math":50, "physics":60}]

Decoding: The decode() function is used to convert the JSON object into python-format type. 

Syntax:

demjson.decode(self, obj)

Example 2: Decoding using demjson package 

Python3




var = '{"a":0, "b":1, "c":2, "d":3, "e":4}'
text = demjson.decode(var)


Output: 

{'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}

Example 3: Encoding using iterencode package  

Python3




# Other Method of Encoding
json.JSONEncoder().encode({"foo": ["bar"]})
'{"foo": ["bar"]}'
 
# Using iterencode(object) to encode a given object.
for i in json.JSONEncoder().iterencode(bigobject):
    mysocket.write(i)


Example 4: Encoding and Decoding using dumps() and loads().

Python3




# To encode and decode operations
import json
var = {'age':31, 'height':6}
x = json.dumps(var)
y = json.loads(x)
print(x)
print(y)
 
# when performing from a file in disk
with open("any_file.json", "r") as readit:
    x = json.load(readit)
print(x)


Command-Line Usage

The JSON library can also be used from the command-line, to validate and pretty-print your JSON.

$ echo "{ \"name\": \"Monty\", \"age\": 45 }"

Searching through JSON with JMESPath

JMESPath is a query language for JSON. It allows you to easily obtain the data you need from a JSON document. If you ever worked with JSON before, you probably know that it’s easy to get a nested value. For example, doc[“person”][“age”] will get you the nested value for age in a document.

First, install jmespath : 

$ pip3 install jmespath

Real-World Example: 

Let us take a real-life example of the implementation of the JSON in python. A good source for practice purposes is JSON_placeholder, it provides a great API requests package which we will be using in our example. To get started, follow these simple steps. Open Python IDE or CLI and create a new script file, name it sample.py. 

Python3




import requests
import json
 
# Now we have to request our JSON data through
# the API package
res = requests.get("https://jsonplaceholder.typicode.com / todos")
var = json.loads(res.text)
 
# To view your Json data, type var and hit enter
var
 
# Now our Goal is to find the User who have
# maximum completed their task !!
# i.e we would count the True value of a
# User in completed key.
# {
    # "userId": 1,
    # "id": 1,
    # "title": "Hey",
    # "completed": false,  # we will count
                           # this for a user.
# }
 
# Note that there are multiple users with
# unique id, and their task have respective
# Boolean Values.
 
def find(todo):
    check = todo["completed"]
    max_var = todo["userId"] in users
    return check and max_var
 
# To find the values.
 
Value = list(filter(find, todos))
 
# To write these value to your disk
 
with open("sample.json", "w") as data:
    Value = list(filter(keep, todos))
    json.dump(Value, data, indent = 2)


To know more, Click Here



Similar Reads

Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
json.loads() vs json.loads() in Python
orjson.loads() and json.loads() are both Python methods used to deserialize (convert from a string representation to a Python object) JSON data. orjson and json are both Python libraries that provide functions for encoding and decoding JSON data. However, they have some differences in terms of performance and compatibility. json is a built-in Pytho
4 min read
Python | Working with the Image Data Type in pillow
In this article, we will look into some attributes of an Image object that will give information about the image and the file it was loaded from. For this, we will need to import image module from pillow. Image we will be working on : size() method - It helps to get the dimensions of an image. IMG = Image.open(Image_path) croppedIm = IMG.size # imp
2 min read
How to Parse Data From JSON into Python?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write for machines to parse and generate. Basically it is used to represent data in a specified format to access and work with data easily. Here we will learn, how to create and parse data from JSON and work with it. Before starting the det
2 min read
Working with Binary Data in Python
Alright, lets get this out of the way! The basics are pretty standard: There are 8 bits in a byteBits either consist of a 0 or a 1A byte can be interpreted in different ways, like binary octal or hexadecimal Note: These are not character encodings, those come later. This is just a way to look at a set of 1's and 0's and see it in three different wa
5 min read
Convert JSON data Into a Custom Python Object
Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parameter is used so that, when we execute json.loads(),
2 min read
How to communicate JSON data between Python and Node.js ?
The following article covers how to communicate JSON data between Python and Node.js. Suppose we are working with the Node.js application, and we want to make use of a specific library that is only available in python or vice versa. We should be able to share the results from one language to another and to achieve it, we will use the JSON as it is
7 min read
Working with Geospatial Data in Python
Spatial data, also known as geospatial data, GIS data, or geodata, is a type of numeric data that defines the geographic location of a physical object, such as a building, a street, a town, a city, a country, or other physical objects, using a geographic coordinate system. You may determine not just the position of an object, but also its length, s
14 min read
Fetch JSON URL Data and Store in Excel using Python
In this article, we will learn how to fetch the JSON data from a URL using Python, parse it, and store it in an Excel file. We will use the Requests library to fetch the JSON data and Pandas to handle the data manipulation and export it to Excel. Fetch JSON data from URL and store it in an Excel file in PythonThe process of fetching JSON data from
3 min read
How to Convert Models Data into JSON in Django ?
Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc. How to Convert Models Data Into Json Data In Django ? First create new
2 min read
How to get JSON data from request in Django?
Handling incoming JSON data in Django is a common task when building web applications. Whether you're developing an API or a web service, it's crucial to understand how to parse and use JSON data sent in requests. In this article, we will create a simple Django project to demonstrate how to retrieve and handle JSON data from incoming requests. Wher
2 min read
JSON Formatting in Python
JSON (JavaScript Object Notation) is a popular data format that is used for exchanging data between applications. It is a lightweight format that is easy for humans to read and write, and easy for machines to parse and generate. Python Format JSON Javascript Object Notation abbreviated as JSON is a lightweight data interchange format. It encodes Py
3 min read
Working with Datetime Objects and Timezones in Python
In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module. Getting a Datetime objectMethod 1: Using now() method A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/ob
5 min read
Internal working of list in Python
Introduction to Python lists : Python lists are internally represented as arrays. The idea used is similar to implementation of vectors in C++ or ArrayList in Java. The costly operations are inserting and deleting items near the beginning (as everything has to be moved). Insert at the end also becomes costly if preallocated space becomes full.We ca
3 min read
Internal working of Python
Python is an object-oriented programming language like Java. Python is called an interpreted language. Python uses code modules that are interchangeable instead of a single long list of instructions that was standard for functional programming languages. The standard implementation of Python is called "cpython". It is the default and widely used im
5 min read
Python | Working with Pandas and XlsxWriter | Set - 1
Python Pandas is a data analysis library. It can read, filter and re-arrange small and large datasets and output them in a range of formats including Excel. Pandas writes Excel files using the XlsxWriter modules. XlsxWriter is a Python module for writing files in the XLSX file format. It can be used to write text, numbers, and formulas to multiple
3 min read
Python | Working with Pandas and XlsxWriter | Set – 2
Prerequisite: : Python working with pandas and xlsxwriter | set-1 Python Pandas is a data analysis library. It can read, filter and re-arrange small and large datasets and output them in a range of formats including Excel. Pandas writes Excel files using the XlsxWriter modules. XlsxWriter is a Python module for writing files in the XLSX file format
4 min read
Python | Working with Pandas and XlsxWriter | Set – 3
Prerequisite: : Python working with pandas and xlsxwriter | set-1 Python Pandas is a data analysis library. It can read, filter and re-arrange small and large datasets and output them in a range of formats including Excel. Pandas writes Excel files using the XlsxWriter modules. XlsxWriter is a Python module for writing files in the XLSX file format
5 min read
Python | Working with PNG Images using Matplotlib
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002. One of the greatest benefits of visualization is that it allows us visual access to hug
3 min read
Python | Working with buttons in Kivy with .kv file
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. Button: The Button is a Label with associated actions that are triggered when the button is pressed (or released a
4 min read
Change current working directory with Python
The OS module in Python is used for interacting with the operating system. This module comes under Python's standard utility module so there is no need to install it externally. All functions in OS module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by
2 min read
Convert JSON to CSV in Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
3 min read
Reading and Writing JSON to a File in Python
The full form of JSON is Javascript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
3 min read
Read, Write and Parse JSON using Python
JSON is a lightweight data format for data interchange that can be easily read and written by humans, and easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called JSON. Example of JSON String s = '{"id":01, "name": "Emily", "language": ["C++", "Python"]}
4 min read
Convert Text file to JSON in Python
JSON (JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modul
4 min read
Internal Working of the len() Function in Python
The len() function in Python has a very peculiar characteristic that one had often wondered about. It takes absolutely no time, and equal time, in calculating the lengths of iterable data structures(string, array, tuple, etc.), irrespective of the size or type of data. This obviously implies O(1) time complexity. But have you wondered How? Python f
2 min read
Saving Text, JSON, and CSV to a File in Python
Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats. Opening a text file in Python Opening a file refers to getting the file ready either for reading or for writing. This can be don
5 min read
Flattening JSON objects in Python
JSON(JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard module
3 min read
Pretty Print JSON in Python
JSON is a javascript notation of storing and fetching the data. Data is usually stored in JSON, XML or in some other database. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Read, Write and Parse JSON using Python Pretty Print JSON Whenever d
2 min read
Article Tags :
Practice Tags :