The ‘json‘ module can be used to read JSON files in Python.
In this short guide, you’ll see several examples of reading JSON files using Python.
Example of Reading a JSON File in Python
Here is an example of a simple JSON file called example.json:
{
"product": "Computer",
"price": 1300,
"brand": "A"
}
To read that JSON file using Python:
import json # Specify the path to your JSON file file_path = "example.json" # Open the file in read mode with open(file_path, "r") as file: data = json.load(file) # Get the full data print(data)
The result:
{'product': 'Computer', 'price': 1300, 'brand': 'A'}
To access specific data from the JSON file:
import json # Specify the path to your JSON file file_path = "example.json" # Open the file in read mode with open(file_path, "r") as file: data = json.load(file) # Access the data print("Product:", data["product"]) print("Price:", data["price"]) print("Brand:", data["brand"])
The result:
Product: Computer
Price: 1300
Brand: A
Additional Examples of Different JSON files
Example 1: Simple Nested JSON
The JSON file:
{ "product": { "name": "Computer", "price": 1300, "shop_address": { "city": "Remote City", "country": "Remote Country" } } }
The Python script to read the JSON file:
import json # Specify the path to your JSON file file_path = "example.json" # Open the file in read mode with open(file_path, "r") as file: data = json.load(file) # Access the data print("Name:", data["product"]["name"]) print("Price:", data["product"]["price"]) print("City:", data["product"]["shop_address"]["city"]) print("Country:", data["product"]["shop_address"]["country"])
The result:
Name: Computer
Price: 1300
City: Remote City
Country: Remote Country
Example 2: List of Objects
The JSON file:
[
{"product": "Computer", "price": 1300},
{"product": "Printer", "price": 150},
{"product": "Keyboard", "price": 50}
]
The Python script:
import json # Specify the path to your JSON file file_path = "example.json" # Open the file in read mode with open(file_path, "r") as file: data = json.load(file) # Access data in the list for item in data: print("Name:", item["product"]) print("Price:", item["price"]) print("-----")
The result:
Name: Computer
Price: 1300
-----
Name: Printer
Price: 150
-----
Name: Keyboard
Price: 50
-----