How to Read a JSON File in Python
json.load(): with open("data.json", encoding="utf-8") as f: data = json.load(f). You get ordinary dictionaries, lists, strings, numbers, booleans and None.JSON is the standard format for configuration files and web APIs. Python's built-in json module converts JSON text into Python objects, so a JSON object becomes a dictionary and a JSON array becomes a list. From that point on you work with it like any other Python data.
The key distinction to remember: json.load() reads from a file object, while json.loads() (with an "s") reads from a string. The examples write a small JSON file first so you can run them as they are.
| Module | import json (standard library) |
|---|---|
| From a file | json.load(f) |
| From a string | json.loads(text) |
| Mapping | object to dict, array to list, true/false to True/False, null to None |
| Invalid JSON raises | json.JSONDecodeError (a subclass of ValueError) |
Read a JSON file with json.load()
Open the file in text mode and pass the file object to json.load(). The returned value depends on the file's top level: usually a dictionary or a list.
import json
with open("student.json", "w", encoding="utf-8") as f:
f.write('{"name": "Asha", "scores": [90, 85], "active": true}')
with open("student.json", encoding="utf-8") as f:
student = json.load(f)
print(student["name"])
print(student["scores"][1])
print(student["active"])Parse a JSON string with json.loads()
When the JSON is already in a variable, for example from an API response, use json.loads(). The s stands for string. It is the same parser, just a different source. See JSON in Python for more, and converting JSON to a dictionary for the string case in depth.
Access nested JSON values safely
Real JSON is often nested. Chain keys and indexes, and use dict.get() when a key may be missing so you get a default instead of a KeyError.
import json
text = '{"user": {"name": "Ravi", "address": {"city": "Pune"}}}'
data = json.loads(text)
print(data["user"]["address"]["city"])
print(data["user"].get("phone", "not given"))See nested data for more patterns.
Handle missing files and invalid JSON
Two things commonly go wrong: the file does not exist (FileNotFoundError) or its content is not valid JSON (json.JSONDecodeError). Wrap the read in try/except when the file comes from outside your program. Typical causes of invalid JSON are single quotes, trailing commas and comments, none of which JSON allows.
json.load() vs json.loads() and how types map
| JSON | Python | Notes |
|---|---|---|
{"a": 1} (object) | dict | Keys are always strings |
[1, 2] (array) | list | |
"text" | str | |
1 / 1.5 | int / float | |
true / false | True / False | Lowercase in JSON |
null | None |
Examples you can run
Press Run, then edit the code and run it again.
Load a configuration file
Read the file once, then use the dictionary like any other.
import json
with open("config.json", "w", encoding="utf-8") as f:
f.write('{"theme": "dark", "font_size": 14, "debug": false}')
with open("config.json", encoding="utf-8") as f:
config = json.load(f)
print(config["theme"])
print(config["font_size"] + 2)
print(config["debug"])Expected outputdark
16
False
Loop over a JSON array of objects
A top-level array becomes a list of dictionaries.
import json
with open("cart.json", "w", encoding="utf-8") as f:
f.write('[{"item": "pen", "price": 10}, {"item": "book", "price": 120}]')
with open("cart.json", encoding="utf-8") as f:
cart = json.load(f)
for entry in cart:
print(entry["item"], entry["price"])
print(sum(entry["price"] for entry in cart))Expected outputpen 10
book 120
130
Catch invalid JSON
A trailing comma is not allowed in JSON, so parsing fails with a JSONDecodeError.
import json
broken = '{"name": "Asha",}'
try:
json.loads(broken)
except json.JSONDecodeError:
print("invalid JSON")Expected outputinvalid JSON
Edge case: JSON null and missing keys
null becomes None, and get() avoids a KeyError.
import json
data = json.loads('{"name": "Meera", "nickname": null}')
print(data["nickname"])
print(data.get("age"))
print(data.get("age", 0))Expected outputNone
None
0
Common mistakes
Passing a file name to json.load()
✗ Wrong
import json
data = json.load("data.json")✓ Right
import json
with open("data.json", "w") as f:
f.write('{"a": 1}')
with open("data.json") as f:
print(json.load(f))json.load() needs an open file object. Open the file first, or use json.loads() for strings.
Using single quotes in JSON text
✗ Wrong
import json
print(json.loads("{'name': 'Asha'}"))✓ Right
import json
print(json.loads('{"name": "Asha"}'))JSON requires double quotes. Fix the source, or build the text with json.dumps().
Expecting a key that is not there
✗ Wrong
import json
data = json.loads('{"name": "Asha"}')
print(data["age"])✓ Right
import json
data = json.loads('{"name": "Asha"}')
print(data.get("age", "unknown"))Use data.get("age") or check "age" in data first.
How to Read a JSON File in Python: questions people ask
How do I read a JSON file in Python?
Use json.load() with an open file: with open("data.json") as f: data = json.load(f). The result is a normal dictionary or list.
What is the difference between json.load() and json.loads()?
json.load() reads JSON from a file object, while json.loads() parses JSON from a string. The extra s stands for string.
How do I write a Python dictionary to a JSON file?
Use json.dump(data, f, indent=2) with a file opened for writing. json.dumps() returns the JSON as a string instead.
Keep learning
Step-by-step lessons:
Working with JSON in PythonPython File HandlingPython Dictionaries
Related:
How to Convert JSON to a Dictionary in PythonHow to Write to a File in PythonHow to Read a CSV File in PythonHow to Check if a File Exists in Python
More in files and data:
How to Read a File Line by Line in PythonHow to Write to a File in PythonHow to Read a CSV File in PythonHow to Check if a File Exists in Python See all →