PythonMastery

How do I read a JSON file in Python?

json.load(f) reads a file, json.loads(text) parses a string. Objects become dicts, arrays become lists, and bad JSON raises JSONDecodeError with the line.

Two functions, and the only difference is the s: json.load reads from an open file, json.loads parses a string you already have.

python
import json

# Make a file to read. Skip this part if you already have one.
with open("config.json", "w", encoding="utf-8") as f:
    f.write('{"site": "pythonmastery", "debug": false, "ports": [8000, 8001]}')

with open("config.json", encoding="utf-8") as f:
    config = json.load(f)

print(config["site"])
print(config["ports"][0])
print(type(config["debug"]))
output
pythonmastery
8000
<class 'bool'>

JSON objects become dictionaries, arrays become lists, true/false become True/False, and null becomes None.

Parsing a string, such as an API response

python
import json

body = '{"user": {"name": "Hedy", "languages": ["python", "go"]}}'
data = json.loads(body)

print(data["user"]["name"])
print(", ".join(data["user"]["languages"]))
output
Hedy
python, go

If the text came from requests, skip this step: response.json() does the same parse for you.

When a key might be missing

data["email"] raises KeyError if the key isn't there. For optional fields, use .get() with a default.

python
import json

user = json.loads('{"name": "Hedy"}')
print(user.get("email", "no email on file"))
output
no email on file

When it won't parse

JSONDecodeError tells you the line and column where parsing gave up. The usual causes are single quotes (JSON only allows "), a trailing comma after the last item, or a file that is actually empty or HTML. The error page goes through each one.

python
import json

try:
    json.loads("{'name': 'Hedy'}")
except json.JSONDecodeError as e:
    print(e)
output
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Go deeper: CSV, JSON, and JSONL — Structured Text Done Right, json.JSONDecodeError: Expecting value, Dictionaries

More short answers

all questions