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