The Wayback Machine - https://web.archive.org/web/20240826180453/https://www.geeksforgeeks.org/read-json-file-using-python/
Open In App

Read JSON file using Python

Last Updated : 28 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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-string which contains the value in key-value mapping within { }.

Python Parse JSON – How to Read a JSON File

It’s pretty easy to load a JSON object in Python. Python has a built-in package called JSON , which can be used to work with JSON data. It’s done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.

Reading JSON files in python is a basic concept while handling data in the python. There are different files you need to handle while working with data in python. If you wish to become ML engineer these are basic you need to understand in detail for the same we have crafted a Complete Machine Learning & Data Science Program in which all aspects are covered that are needed to become a good ML engineer.

Deserialize a JSON String to an Object in Python

The Deserialization of JSON means the conversion of JSON objects into their respective Python objects. The load()/loads() 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()/loads(), which is usually used to load from string, otherwise, the root object is in list or dict. See the following table given below.

JSON OBJECT

PYTHON OBJECT

object

dict

array

list

string

str

null

None

number (int)

int

number (real)

float

true

True

false

False

json.load() method

The json.load() accepts the file object, parses the JSON data, populates a Python dictionary with the data, and returns it back to you.

Syntax:

json.load(file object)

Parameter: It takes the file object as a parameter.

Return: It return a JSON Object.

Loading a JSON File in Python

Here we are going to read a JSON file named data.json the screenshot of the file is given below.

python-json

In the below code, firstly we import the JSON module, open the file using the file handling open() function , and then store the data into the variable ‘data’ using the json.load() function. After that, we iterate over the data and print it.

Python
# Python program to read
# json file

import json

# Opening JSON file
f = open('data.json')

# returns JSON object as 
# a dictionary
data = json.load(f)

# Iterating through the json
# list
for i in data['emp_details']:
    print(i)

# Closing file
f.close()

Output:

python-read-json-output

json.loads() Method

If we have a JSON string, we can parse it by using the json.loads() method . json.loads() does not take the file path, but the file contents as a string, to read the content of a JSON file we can use fileobject.read() to convert the file into a string and pass it with json.loads(). This method returns the content of the file.

Syntax:

json.loads(S)

Parameter: it takes a string, bytes, or byte array instance which contains the JSON document as a parameter (S).

Return Type: It returns the Python object.

Python – Read JSON String

This example shows reading from both string and JSON file using json.loads() method. Firstly, we have a JSON string stored in a variable ‘j_string’ and convert this JSON string into a Python dictionary using json.loads() method that is stored in the variable ‘y’ after that we print it. Secondly, we read JSON String stored in a file using json.loads() for that we first convert the JSON file into a string using the file handling same as in the above example and then convert it into the string using read() function and rest of the procedure is same as we follow before using json.loads() method.

Python
# Python program to read
# json file

import json

# JSON string
j_string = '{"name": "Bob", "languages": "English"}'

# deserializes into dict and returns dict.
y = json.loads(j_string)

print("JSON string = ", y)
print()

# JSON file
f = open ('data.json', "r")

# Reading from file
data = json.loads(f.read())

# Iterating through the json list
for i in data['emp_details']:
    print(i)

# Closing file
f.close()

Explanation: Here in the output we can see both the output of the reading string and file using json.loads() method

Output:

python-read-json-output

Read JSON file using Python – FAQs

How to convert the JSON data into Python objects?

We can use the json.loads() function from the json module to convert JSON data (in string format) into Python objects (like dictionaries or lists).

import json
json_data = '{"name": "John", "age": 30}'
python_obj = json.loads(json_data)

Here, python_obj will be a Python dictionary representing the JSON data.

What is the best Python library for reading JSON files?

The json module, which comes built-in with Python, is widely used and efficient for reading and writing JSON data. For more advanced features and utilities, libraries like pandas or requests can also handle JSON effectively.

What are the steps to load and access data from a JSON file using Python?

Steps to load and access data from a JSON file:

  1. Read the JSON file : Use open() to read the file content.
  2. Parse JSON data : Use json.load() to parse the JSON data into Python objects.
  3. Access the data : Use standard Python techniques to access the data (e.g., dictionary keys or list indices).
import json
# Load data from JSON file
with open('data.json', 'r') as f:
data = json.load(f)
# Accessing data
print(data['key'])

How to read nested JSON in Python?

Access nested JSON data by chaining keys (for dictionaries) or indices (for lists) together. For example:

import json
json_data = '{"person": {"name": "John", "age": 30}}'
data = json.loads(json_data)
# Accessing nested data
print(data['person']['name']) # Output: John

What is a simple example of reading JSON data in Python?

Simple example of reading JSON data from a file:

import json
# Load data from JSON file
with open('data.json', 'r') as f:
data = json.load(f)
# Print the loaded data
print(data)


Similar Reads

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
Read content from one file and write it into another file
Prerequisite: Reading and Writing to text files in Python Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be handled in python, normal text files and binary files (written in binary language,0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character call
2 min read
How to read a JSON response from a link in Python?
There is a huge amount of data available on the web and most of them are in form of (JavaScript Object Notation) JSON. But it is difficult for humans to directly read and use it. To resolve this problem in python we have different libraries which help us to read the JSON data fetched from the web. These libraries have objects and functions which he
2 min read
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
How to Read JSON Files with Pandas?
In this article, we are going to see how to read JSON Files with Pandas. Reading JSON Files Using PandasTo read the files, we use the read_json() function and through it, we pass the path to the JSON file we want to read. Once we do that, it returns a "DataFrame"( A table of rows and columns) that stores data. If we want to read a file that is loca
3 min read
Read Properties File Using jproperties in Python
In this article, we are going to see how to read properties file in python using jproperties module. It is a Java Property file parser and writer for Python. For installation run this command into your terminal. pip install jproperties Various properties of this module: get() Method or Index-Based access to reading the values associated with the ke
2 min read
How to import JSON File in MongoDB using Python?
Prerequisites: MongoDB and Python, Working With JSON Data in Python MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. JSON stands for JavaScript Object Notation. It is an open standard file format, and data int
2 min read
Append to JSON file using 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-
2 min read
Read a Particular Page from a PDF File in Python
Document processing is one of the most common use cases for the Python programming language. This allows the language to process many files, such as database files, multimedia files and encrypted files, to name a few. This article will teach you how to read a particular page from a PDF (Portable Document Format) file in Python. Method 1: Using Pymu
4 min read
How to read from a file in Python
Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line
5 min read
Python program to read character by character from a file
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it. Example Input: GeeksOutput: G e e k sExplanation: Iterated through character by character from the input as shown in the output.Read a fi
2 min read
Python program to read file word by word
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file word by word. Read file word by wordIn this article, we will look at how to read a text file and split it into single words using Python. Here are a few examples of reading a file word by word in Python for a bette
2 min read
Upload file and read its content in cherrypy python
CherryPy is a web framework of Python which provides a friendly interface to the HTTP protocol for Python developers. It is also called a web application library. It allows developers to build web applications in much the same way they would build any other object-oriented Python program. This results in smaller source code developed in less time.
3 min read
Read List of Dictionaries from File in Python
A dictionary in Python is a collection where every value is mapped to a key. Since they are unordered and there is no constraint on the data type of values and keys stored in the dictionary, it is tricky to read dictionaries from files in Python. Read a List of Dictionary from Text Files in PythonUsing Pickle ModuleUsing read( ) MethodThe problem s
3 min read
How to read Dictionary from File in Python?
A Dictionary in Python is collection of key-value pairs, where key is always unique and oftenly we need to store a dictionary and read it back again. We can read a dictionary from a file in 3 ways: Using the json.loads() method : Converts the string of valid dictionary into json form. Using the ast.literal_eval() method : Function safer than the ev
2 min read
How to read a numerical data or file in Python with numpy?
Prerequisites: Numpy NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. This article depicts how numeric data can be read from a file using Numpy. Numerical data can be present in different formats of file : The data can be saved in a txt file wh
4 min read
Python - Read file from sibling directory
In this article, we will discuss the method to read files from the sibling directory in Python. First, create two folders in a root folder, and one folder will contain the python file and the other will contain the file which is to be read. Below is the dictionary tree: Directory Tree: root : | |__Sibling_1: | \__demo.py | |__Sibling_2: | \__file.t
3 min read
How to Read Text File Into List in Python?
In this article, we are going to see how to read text files into lists in Python. File for demonstration: Example 1: Converting a text file into a list by splitting the text on the occurrence of '.'. We open the file in reading mode, then read all the text using the read() and store it into a variable called data. after that we replace the end of t
2 min read
Read a text file into a string variable and strip newlines in Python
It is quite a common requirement for users to remove certain characters from their text files while displaying. This is done to assure that only displayable characters are displayed or data should be displayed in a specific structure. This article will teach you how to read a text file into a string variable and strip newlines using Python. For dem
5 min read
Read File As String in Python
Python provides several ways to read the contents of a file as a string, allowing developers to handle text data with ease. In this article, we will explore four different approaches to achieve this task. Each approach has its advantages and uses cases, so let's delve into them one by one. Read File As String In PythonBelow are some of the approach
3 min read
Read CSV File without Unnamed Index Column in Python
Whenever the user creates the data frame in Pandas, the Unnamed index column is by default added to the data frame. The article aims to demonstrate how to read CSV File without Unnamed Index Column using index_col=0 while reading CSV. Read CSV File without Unnamed Index Column Using index_col=0 while reading CSVThe way of explicitly specifying whic
2 min read
How to read specific lines from a File in Python?
Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers begin with the 0th index. There are various ways
3 min read
Read a file without newlines in Python
When working with files in Python, it's common to encounter scenarios where you need to read the file content without including newline characters. Newlines can sometimes interfere with the processing or formatting of the data. In this article, we'll explore different approaches to reading a file without newlines in Python. Read a file without newl
2 min read
Read a file line by line in Python
Prerequisites: Open a file Access modes Close a file Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file. Learning Ef
7 min read
Saving scraped items to JSON and CSV file using Scrapy
In this article, we will see how to use crawling with Scrapy, and, Exporting data to JSON and CSV format. We will scrape data from a webpage, using a Scrapy spider, and export the same to two different file formats. Here we will extract from the link http://quotes.toscrape.com/tag/friendship/. This website is provided by the makers of Scrapy, for l
5 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
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
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
Writing Scrapy Python Output to JSON file
In this article, we are going to see how to write scrapy output into a JSON file in Python. Using scrapy command-line shell This is the easiest way to save data to JSON is by using the following command: scrapy crawl <spiderName> -O <fileName>.json This will generate a file with a provided file name containing all scraped data. Note tha
2 min read