How to read JSON file in Python

PythonServer Side ProgrammingProgramming

What is a JSON file?

JSON stands for JavaScript Object Notation. It is commonly used for transmitting data in web applications( such as sending data from server to client to display on the web pages).

Sample JSON File

Example 1:
{
   "fruit": "Apple",
   "size": "Large",
   "color": "Red"
}


Example 2:
{
   'name': 'Karan',
   'languages': ['English', 'French']
}

The json file will have .json extension

Read JSON file in Python

Python has an in-built package called json which can be used to work with JSON data and to read JSON files. The json module has many functions among which load() and loads() are used to read the json files.

load() − This function is used to parse or read a json file.

loads() − This function is used to parse a json string.

To use json module in python, we need to import it first. The json module is imported as follows −

import json

Suppose we have json file named “persons.json” with contents as shown in Example 2 above. We want to open and read it using python. This can be done in following steps −

  • Import json module

  • Open the file using the name of the json file witn open() function

  • Open the file using the name of the json file witn open() function

  • Read the json file using load() and put the json data into a variable.

  • Use the data retrieved from the file or simply print it as in this case for simplicty.

Example

import json

with open('persons.json') as f:
   data = json.load(f)

print(data)

Output

{'name': 'Karan', 'languages': ['English', 'French']}

Note:

  • Make sure the json file is saved with .json extension on your system.

  • Make sure the json file and the python program are saved in the same directory on your system, else an exception would be raised.

raja
Published on 11-Jun-2021 12:30:25
Advertisements