The Wayback Machine - https://web.archive.org/web/20240814032717/https://www.geeksforgeeks.org/read-write-and-parse-json-using-python/
Open In App

Read, Write and Parse JSON using Python

Last Updated : 07 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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"]}'

The syntax of JSON is considered a subset of the syntax of JavaScript including the following:

  • Name/Value pairs: Represents Data, the name is followed by a colon(:), and the Name/Value pairs are separated by a comma(,).
  • Curly braces: Holds objects.
  • Square brackets: Hold arrays with values separated by a comma (,).

Keys/Name must be strings with double quotes and values must be data types amongst the following: 

Example of JSON file:

 {
"employee": [
{
"id": "01",
"name": "Amit",
"department": "Sales"
},
{
"id": "04",
"name": "sunil",
"department": "HR"
}
]
}

Python Parse JSON String

In the below code, we are going to convert JSON to a Python object. To parse JSON string Python firstly we import the JSON module. We have a JSON string stored in a variable ’employee’ and we convert this JSON string to a Python object using json.loads() method of JSON module in Python. After that, we print the name of an employee using the key ‘name’ .

Python3




# Python program to convert JSON to Python
import json
 
# JSON string
employee ='{"id":"09", "name": "Nitin", "department":"Finance"}'
 
# Convert string to Python dict
employee_dict = json.loads(employee)
print(employee_dict)
 
print(employee_dict['name'])


Output

{'id': '09', 'name': 'Nitin', 'department': 'Finance'}
Nitin

Python read JSON file

Let’s suppose we have a JSON file that looks like this.

pyhton-append-json1

Here, we have used the open() function to read the JSON file. Then, the file is parsed using json.load() method which gives us a dictionary named data.

Python3




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-output1

Convert Python Dict to JSON

In the below code, we are converting a Python dictionary to a JSON object using json.dumps() method of JSON module in Python. We first import the JSON module and then make a small dictionary with some key-value pairs and then passed it into json.dumps() method with ‘indent=4’ to convert this Python dictionary into a JSON object. As we have given the value of indent to 4 there are four whitespaces before each data as seen in the output.

Python3




# Python program to convert
# Python to JSON
import json
  
# Data to be written
dictionary = {
  "id": "04",
  "name": "sunil",
  "department": "HR"
}
  
# Serializing json
json_object = json.dumps(dictionary, indent = 4)
print(json_object)


Output

{
    "id": "04",
    "name": "sunil",
    "department": "HR"
}

The following types of Python objects can be converted into JSON strings: 

Python objects and their equivalent conversion to JSON:

Python

JSON Equivalent

dict

object

list, tuple

array

str

string

int, float

number

True

true

False

false

None

null

Writing JSON to a file in Python

We can write JSON to file using json.dump() function of JSON module and file handling in Python. In the below program, we have opened a file named sample.json in writing mode using ‘w’. The file will be created if it does not exist. Json.dump() will transform the Python dictionary to a JSON string and it will be saved in the file sample.json.

Python3




# Python program to write JSON
# to a file
import json
  
# Data to be written
dictionary ={
    "name" : "sathiyajith",
    "rollno" : 56,
    "cgpa" : 8.6,
    "phonenumber" : "9976770500"
}
  
with open("sample.json", "w") as outfile:
    json.dump(dictionary, outfile)


Output:

python-json-write-to-file

Python Pretty Print JSON

When we convert a string to JSON the data is in a less readable format. To make it more readable we can use pretty printing by passing additional arguments in json.dumps() function such as indent and sort_keys as used in the below code.

Python3




# Python program to convert JSON to Python
import json
 
# JSON string
employee ='{"id":"09", "name": "Nitin", "department":"Finance"}'
 
# Convert string to Python dict
employee_dict = json.loads(employee)
 
# Pretty Printing JSON string back
print(json.dumps(employee_dict, indent = 4, sort_keys= True))


Output

{
    "department": "Finance",
    "id": "09",
    "name": "Nitin"
}


Similar Reads

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
Pyspark - Parse a Column of JSON Strings
In this article, we are going to discuss how to parse a column of json strings into their own separate columns. Here we will parse or read json string present in a csv file and convert it into multiple dataframe columns using Python Pyspark. Example 1: Parse a Column of JSON Strings Using pyspark.sql.functions.from_json For parsing json string we'l
4 min read
Read and Write TOML Files Using Python
TOML file stand for (Tom's Obvious, Minimum Language). The configuration files can be stored in TOML files, which have the .toml extension. Due to its straightforward semantics, which strives to be "minimal," it is supposed to be simple to read and write. It is also made to clearly map to a dictionary. The TOML's syntax primarily consists of key =
6 min read
Read 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-
6 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
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 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
Parse XML using Minidom in Python
DOM (document object model) is a cross-language API from W3C i.e. World Wide Web Consortium for accessing and modifying XML documents. Python enables you to parse XML files with the help of xml.dom.minidom, which is the minimal implementation of the DOM interface. It is simpler than the full DOM API and should be considered as smaller. Steps for Pa
1 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg