In this tutorial, we will discuss how can we read and write to JSON file in Python? with examples.

JSON (JavaScript Object Notation) is a lightweight format to interchange data. It is the text form of a javascript object. The key is of type “string “with double quotation marks and values can be string, number, nested json or array of the same.

Example:

{ 
  "lang"     : "python",
  "version"  : 3, 
  "website"  : "pencilprogrammer.com"
}

JSON data is stored in JSON file (file with .json extension).

In Python, json.load() and json.loads() are the two methods used to read JSON data.

  • json.load() read JSON encoded data from JSON file and convert it into Python dictionary.
  • json.loads() parse JSON string into Python dictionary.

We should not get confused between the two methods. For encoded data stored in a file ,json.load() method is used whereas for JSON data in the form of string json.loads() method is used.

Let’s see an example of it.

Example: Read JSON File in Python

import json

#open json file
data_file = open('data.json')

'''
parse json encoded data into dictionary
using json.load()
'''
data_dict= json.load(data_file)

print(data_dict)

Output

read json file in python

The data.json contains the encoded JSON data. We first load it into our program then we parse it into dictinary using json.load().

Example: Read JSON String in Python

In the above example, we read a JSON file. In this python example will read a JSON string and parse it into a dictionary using JSON.loads().

import json

#JSON String
json_string = '{ "website"  : "pencilprogrammer.com" }'

#JSON data into dictionary
data_dict= json.loads(json_string)

print(data_dict)

Output

Read JSON String in Python

If you have any doubts or suggestion then please comment below.

Leave a Reply

7 + eight =