Python Introduction

Python JSON: Read, Write, Parse JSON (With Examples)

In this tutorial, we will explain the concept of read JSON file Python and its related operations. Students can learn to parse, read and write JSON in Python with the help of suitable examples. Also, students will learn to convert JSON into the dictionary and pretty print.

Introduction

Expansion of JSON is the JavaScript Object Notation. It is a popular data format used for the representation of structured data. The JSON format is commonly used to transmit and receive data between the server and web application.

In Python, JSON is found in the form of a string.

JSON is a lightweight data format, suitable for data interchange and also it can be easily read and written by humans. Also, it is easily parsed and generated by the machines. Therefore, it is the text format that is completely language-independent. In Python working with the JSON data is being facilitated through the built-in package. This package is “JSON”.

For example

str = ‘{“code”:01, “name”: “Smart”, “language”: [“C++”, “Python”]}’

It is also common for storing a JSON object in a file in python.

Import JSON Module:

To work with JSON in Python as a string or as a file with a JSON object, one has to use Python’s “JSON” module. One has to import this module before its use. Its syntax is:

import JSON

JSON Syntax:

The syntax needed for the JSON is being considered as the subset of the syntax of JavaScript. It is including the following:

  • Name/Value pairs: It represents data, name and followed by ‘:'(colon). Also, the Name/Value pairs is being separated by, (comma).
  • Curly braces: It is used to hold the objects.
  • Square brackets: It is used to hold the arrays with comma-separated values.

Remember that, Keys/Names must be strings enclosed within double quotes. And values must be any one of the following data types:

  • String
  • Number
  • Object (JSON object)
  • array
  • Boolean
  • Null

For example:

                    

{ "staff": [ {  "code": "10",

"name": "Smart",

"office": "Sales" },

{  "code": "12",

"name": "Good",

"office": "Field” }]

}

Parse JSON in Python:

The “JSON” module of Python makes it easy to parse the JSON strings as well as the files containing JSON objects.

Parse JSON will convert from JSON to Python.

JSON.loads() is the function which can parse a JSON string. Its result will be a Python dictionary.

Its syntax is:

json.loads(json_string)

For Example:

                    

# Python program for the conversion of JSON to Python

import json

# JSON string is defined

staff ='{“code”:”10″, “name”: “Smart”, “office”:”Accounts”}’

# Convert the string into Python dictionary

staff_dict = json.loads(staff)

print(staff_dict)

print(“name is”,staff_dict[“name”])

Output:

{‘code’: ’10’, ‘name’: ‘Smart’, ‘office’: ‘Accounts’}

name is Smart

Example: Conversion of Python JSON into dictionary data.

One can parse a JSON string with the help of json.loads() function. This function returns a dictionary.

                    

import json

staff = ‘{“name is”: “DKJ”, “languages”: [“English”, “Hindi”]}’

staff_dict = json.loads(staff) # conversion into dictionary

print( staff_dict)  # To print the complete dictionary

print(staff_dict[“languages”])   # To print the part of dictionary

# Here staff is the python string whereas staff_dict is the converted dictionary.

Output

{‘name is’: ‘DKJ’, ‘languages’: [‘English’, ‘Hindi’]}

[‘English’, ‘Hindi’]

Read JSON file Python:

Built-in function JSON.load() in Python can read a file containing the JSON object. Let us consider a file named staff.json which contains the JSON object. The syntax for using this read function is:

Syntax:

json.load(file_object)

Thus, using the above syntax one can read a file containing JSON object.

Suppose the staff.json file contains a JSON object as follows:

                    

{

“name”: “DKJ”, “expertise” : [“Accounts”, “Finance”]

}

Using the following code one can parse the above file:

import JSON

with open(“path_of_the_file/staff.json”) as myfile:

details=json.load(myfile)

print(details)

Output

{‘name’: ‘DKJ’, ‘expertise’: [‘Accounts’, ‘Finance’]}

In the above code, we have used the open() function for open the json file in read mode. Further, the file is parsed using json.load() function which returns the dictionary named as “details”.

Python Convert to JSON string:

One can convert any dictionary-based data into JSON string by using json.dumps() function.

Its syntax is as follows:

json.dumps(dictionary, indent)

It accepts two parameters. First, one is dictionary which  will be converted into JSON object. Second is indent which defines the number of units for indentation.

                    

import json

staff_dict = {“location”:”Delhi” , “code”: “123” , “status” : “regular”}

staff_json= json.dumps(staff_dict)

print (staff_json)  # To display the output

Output:

{“location”: “Delhi”, “code”: “123”, “status”: “regular”}

Writing JSON content to a file:

To write the contents of JSON to a file in Python, one can use JSON.dump() function. Its syntax is as follows:

json.dump(dictionary, file_pointer)

Above code is accepting two parameters. First one is “dictionary”, which is the content to be written into a file.

Second is “file_pointer” which is pointer of the file opened in write/append mode.

For example following code is to write JSON object to a file.

                    

import json

staff_dict = {“location”:”Delhi” , “code”: “123” , “status” : “regular”}

with open(“staff.txt”, “w”) as my_json_file:

json.dump(staff_dict, my_json_file)

In the above code, we have opened the “staff.txt” file in writing mode. If this file is not already existing then a blank file will be created. Further, json.dump() converts the staff_dict to a JSON string which will be saved in the staff.txt file.

After running the above code staff.txt will have the following text :

staff_dict = {“location”:”Delhi” , “code”: “123” , “status” : “regular”}

Python pretty print JSON:

Prettyprint is the process of conversion and hence the presentation of source code or other objects in a proper, legible and attractive manner. A prettyprinter is accepting the blocks of code and prints attractively and pleasingly. It presents the characters with line breaks and indentations as well. Therefore, for analysing and debugging the JSON data, we have to print it in some better readable format. Thus, pretty print in JSON can be done by passing the additional parameters indent and sort_keys to the functions like json.dumps() and json.dump().

For example: Python pretty print JSON can be done as following:

                    

Import json

staff_string = ‘{“location”:”Delhi” , “code”: “123” , “status” : “regular”}’

staff_dict= json.loads(staff_string)

print(json.dumps(staff_dict, indent=5, sort_keys=True))

# Pretty printing with indentation and sorting

In the above-mentioned code, indentation is of 5 spaces. Also, the keys are sorted in ascending order due to the “True” flag value for the “sort_keys” parameter. It must be noted that the default value of indent will be None, and the default value of sort_keys will be “False”.

Frequently asked questions:

Q1: How do I read a JSON file in Python?

Answer: Built-in function json.load() in the Python library is used to read the content of a JSON file. Such a file may contain any specific JSON object.

Q2: How do I read a JSON file into a DataFrame in Python?

Answer: To read the JSON file into a DataFrame, built-in function read_json() can be used. It also enables us to read the JSON in the DataFrame formate of Pandas. The below-given code is one such example:

                    

import pandas

data = df.read_json(“path_of_json_file.json”)    # df is the data frame

# displaying the content of data frame

print(data)

Q3: How do I extract data from a JSON file in Python?

Answer: To extract the contents from a JSON file, one has to parse the data. Parsing can be done by using the function json.loads().

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.