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:

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

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().

Output

Read JSON String in Python

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

Leave a Reply