Skip to content
The App Code
How-to

Parse JSON in Python

Convert a JSON string into Python dicts and lists with the standard-library json module.

Also known as: json.loads Python, Python decode JSON

beginner

Use json.loads to parse a JSON string into Python objects and json.load to read from a file. It maps objects to dicts, arrays to lists, and JSON values to their Python equivalents.

What it is

The built-in json module handles JSON with no third-party dependency. json.loads(s) parses a string; json.load(f) reads from a file-like object. JSON objects become dict, arrays become list, and true/false/null become True/False/None.

To go the other way, json.dumps(obj) serializes to a string — pass indent=2 for pretty output. Access parsed values like any dict, and use .get("key") when a field might be absent to avoid a KeyError.

Worked example

import json

text = '{"id": 7, "name": "Ada", "active": true}'
data = json.loads(text)

print(data["name"])        # Ada
print(data["active"])      # True (JSON true -> Python True)
print(data.get("missing")) # None, no KeyError

# Serialize back to JSON
print(json.dumps(data, indent=2))

Failure mode — when it misleads

Invalid JSON raises json.JSONDecodeError; wrap parsing in try/except when the input isn't trusted. A frequent mistake is confusing loads/dumps (strings) with load/dump (files) — passing a filename string to json.load fails because it expects a file object, not a path.

Sources & further reading