How to Read a JSON File in Python
Load a JSON file into a Python dictionary with the built-in json module, pull out values and lists, parse a JSON string, and write changes back.
You have a data.json file and want its contents as Python objects. The standard library's json module does this with no extra install.
Load the file
Given this data.json:
{
"name": "Inventory",
"count": 3,
"items": ["bolt", "nut", "washer"],
"owner": {"username": "user", "active": true}
}
Read it with:
import json
with open("data.json") as f:
data = json.load(f)
print(type(data))
<class 'dict'>
json.load takes an open file object and returns a Python object. A JSON object becomes a dict, arrays become lists, numbers become int or float, and true, false, and null become True, False, and None. The with block closes the file for you.
Access the values
print(data["name"])
print(data["items"][0])
print(data["owner"]["username"])
for item in data["items"]:
print(item)
Inventory
bolt
user
bolt
nut
washer
A missing key raises KeyError. Use data.get("missing") to get None instead, or data.get("missing", "default") for a fallback value.
Parse a JSON string instead of a file
If the JSON is already in a string, for example from an API response, use json.loads (load string):
text = '{"status": "ok", "code": 200}'
result = json.loads(text)
print(result["code"])
Pretty-print the data
print(json.dumps(data, indent=2))
json.dumps turns a Python object back into a JSON string. indent=2 spreads it over multiple lines; add sort_keys=True to order the keys alphabetically.
Write changes back to the file
data["count"] = 4
data["items"].append("screw")
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
Opening with "w" replaces the file, so make sure data holds everything you want to keep. json.dump (no s) writes to a file object; json.dumps returns a string.
If you see FileNotFoundError. The path is resolved relative to the directory you ran python3 from, not the script's location. Use an absolute path, or build one from the script's own location: from pathlib import Path then Path(__file__).parent / "data.json".
If you see JSONDecodeError. The file is not valid JSON. Common causes are a trailing comma after the last item, single quotes instead of double quotes, comments, or an empty file. The error message includes the line and column where parsing failed.
More Coding how-tos
- How to Add a .gitignore File
- How to Check Which Node.js Version Is Installed
- How to Check Which Python Version Is Installed
- How to Clone a Git Repository
- How to Connect to a Server with SSH
- How to Create a New Git Branch
- How to Create a Python Virtual Environment
- How to Delete a Git Branch
- How to Install Node.js with nvm
- How to Install Python Packages with pip
- How to Make a Script Executable in the Terminal
- How to Print Hello World in JavaScript
- How to Print Hello World in Python
- How to Resolve a Merge Conflict in Git
- How to Run a Local Web Server in One Command
- How to Set an Environment Variable
- How to Stash Changes in Git
- How to Undo the Last Git Commit
- How to Write Your First Bash Script