How to Read JSON File in Python

Here are 2 ways to read JSON file in Python:

  1. Using json.load()
  2. Using json.loads()

Visual Representation of Python Read JSON File using json.load()

Method 1: Using json.load()

Here is the step-by-step guide :

  1. Import the json module.
  2. You can use built-in open() function to open the file for reading. It’s recommended to use the with statement, which ensures proper handling of the file.
  3. Finally, use json.load() to read from the file and parse the JSON data.

Example

We have already created a file named ‘player.json‘ while demonstrating how to Write JSON to a File. We will use the same file here to help you understand better.

players_json

import json

# Open and read the JSON file
with open('players.json', 'r') as file:
 data = json.load(file)

# Pretty print the JSON data
formatted_data = json.dumps(data, indent=2)
print(formatted_data)

Output

Output of Using json.load()

Method 2: Using json.loads()

The json.loads() function is used to convert the JSON string into a Python object. It takes a string as its argument.

Example

import json

# Parse JSON from a string
str_json_string = '{"name": "Krunal", "Age": "30"}'
str_data = json.loads(str_json_string)
print("JSON string : ", str_data)

# Open and read the content of the JSON file into a string
with open('players.json', 'r') as file:
 json_string = file.read()

# Parse the JSON string into a Python object
data = json.loads(json_string)

# Pretty print the JSON data
formatted_data = json.dumps(data, indent=2)
print(formatted_data)

Output

Output of Using json.loads()

 

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.