Read a JSON file into a Python dict
json.load() reads a file object. json.loads() reads a string. Pass the open file, and check that the top-level value is an object before you use keys.
Load the file with json.load()
To read a JSON file into a dict, open it as text and pass that file object to json.load(). A JSON object becomes a dictionary. Keys in that dictionary are strings.
import json
with open("data.json", encoding="utf-8") as file:
data = json.load(file)
print(data["name"])
For a file that contains {"name": "Ada", "active": true}, data["name"] is "Ada" and data["active"] is True. The context manager closes the file even when parsing fails. encoding="utf-8" matches the encoding JSON uses for exchange. Opening without an encoding uses the platform default, which can misread non-ASCII text.
json.load() does not accept a path. json.load("data.json") raises AttributeError because a string has no read method. Open the file first.
json.load() is for files, json.loads() is for strings
| You have | Call |
|---|---|
A .json file | json.load(file) |
A JSON string or bytes | json.loads(text) |
| One JSON value per line | Read JSON Lines record by record |
| An HTTP response from requests | response.json() |
If the file is already read into a string, json.loads(text) is the right call. That path, including JSONDecodeError on a Python dict pasted as text, is covered in JSON string to dict.
Report a missing file and a bad line separately
import json
try:
with open("data.json", encoding="utf-8") as file:
data = json.load(file)
except FileNotFoundError:
print("data.json is missing")
except json.JSONDecodeError as exc:
print(f"Invalid JSON at line {exc.lineno}, column {exc.colno}")
A missing file and invalid JSON are different failures. Single quotes, True, None, trailing commas, and comments are valid in a Python dict and invalid in a JSON file. Do not pass the file to eval() or ast.literal_eval() to skip the error. If the text is a Python literal rather than JSON, convert it first. The json module documents both loaders.
A JSON file is not always a dict
A file whose top-level value is an array loads as a list. A file that is only null loads as None. Check the type before using key access:
if not isinstance(data, dict):
raise TypeError(f"Expected a JSON object, got {type(data).__name__}")
To write the dict back, use json.dump(). That is a separate step from reading. If parsing returns a string, the file may contain double-encoded JSON.