How to Parse JSON in Python
Last updated:
Python provides 2 JSON parse functions in the standard library: json.loads() for strings and json.load() for file objects — no pip install, available since Python 2.6. Parsing maps 7 JSON types to Python equivalents: object → dict, array → list, string → str, integer → int, float → float, true/false → True/False, and null → None. Errors raise json.JSONDecodeError with exact line and column numbers. For large files, orjson is 2–10x faster than the stdlib and drops in as a 1-line replacement. This guide covers both parse functions, the full 7-type mapping table, error handling patterns, file reading with open(), nested data access, and when to reach for orjson or ujson.
Format and Inspect Python JSON Output
Paste any JSON string from Python to pretty-print, validate syntax, and explore nested structures instantly.
Open JSON FormatterParse a JSON string with json.loads()
json.loads() takes a JSON string and returns a Python object. The "s" stands for "string".
import json
json_string = '{"name": "Alice", "age": 30, "active": true}'
data = json.loads(json_string)
print(data["name"]) # Alice
print(data["age"]) # 30
print(data["active"]) # True
print(type(data)) # <class 'dict'>JSON to Python type mapping
When you parse JSON, Python maps each JSON type to the closest Python equivalent:
| JSON type | Python type | Example |
|---|---|---|
object | dict | {"key": "val"} → {"key": "val"} |
array | list | [1, 2] → [1, 2] |
string | str | "hello" → 'hello' |
number (int) | int | 42 → 42 |
number (float) | float | 3.14 → 3.14 |
true | True | true → True |
false | False | false → False |
null | None | null → None |
Read JSON from a file with json.load()
json.load() reads directly from a file object — no need to read the file content manually first.
import json
# Read a JSON file
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(data) # Python dict/list
print(type(data)) # <class 'dict'>Always specify encoding="utf-8" to handle international characters correctly on all platforms.
Access nested JSON data
After parsing, use dictionary indexing and list indexing to access nested values.
import json
json_string = """
{
"user": {
"name": "Alice",
"address": {
"city": "New York",
"zip": "10001"
},
"scores": [95, 87, 92]
}
}
"""
data = json.loads(json_string)
# Access nested object
city = data["user"]["address"]["city"]
print(city) # New York
# Access array element
first_score = data["user"]["scores"][0]
print(first_score) # 95
# Safe access with .get()
country = data["user"]["address"].get("country", "USA")
print(country) # USA (default value)Parse a JSON array
If the top-level JSON value is an array, json.loads() returns a Python list.
import json
json_string = '[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]'
users = json.loads(json_string)
for user in users:
print(user["id"], user["name"])
# Output:
# 1 Alice
# 2 BobHandle JSON parse errors
json.loads() raises json.JSONDecodeError when the input is invalid JSON. Always wrap it in a try/except block in production code.
import json
def safe_parse(json_string):
try:
return json.loads(json_string)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e.msg} at line {e.lineno}, col {e.colno}")
return None
# Valid JSON
data = safe_parse('{"name": "Alice"}')
print(data) # {'name': 'Alice'}
# Invalid JSON (trailing comma)
data = safe_parse('{"name": "Alice",}')
print(data) # Invalid JSON: Expecting property name... → Nonejson.JSONDecodeError provides .msg, .lineno, and .colno for precise error reporting.
Parse JSON from an API response
When using the requests library, call .json() on the response object — it calls json.loads() internally.
import requests
response = requests.get("https://api.example.com/users/1")
response.raise_for_status() # Raise error for 4xx/5xx
user = response.json() # Returns a Python dict
print(user["name"])Convert JSON to a custom Python class
Use the object_hook parameter to map JSON objects to custom classes automatically during parsing.
import json
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
def user_hook(d):
if "name" in d and "age" in d:
return User(name=d["name"], age=d["age"])
return d
json_string = '{"name": "Alice", "age": 30}'
user = json.loads(json_string, object_hook=user_hook)
print(user) # User(name='Alice', age=30)
print(user.name) # AliceCommon mistakes to avoid
- Single quotes — JSON requires double quotes. Python dicts use single quotes, but
json.loads("{'key': 'val'}")will raise an error. - Trailing commas —
{"a": 1,}is invalid JSON even though Python dicts allow it in source code. - Using
eval()— Never useeval()to parse JSON. It's a security vulnerability. Always usejson.loads(). - Confusing
json.loads()andjson.load()—loads()takes a string,load()takes a file object.
Convert Python dict back to JSON
Use json.dumps() to serialize a Python object back to a JSON string, andjson.dump() to write to a file.
import json
data = {"name": "Alice", "age": 30, "active": True}
# To string
json_string = json.dumps(data, indent=2)
print(json_string)
# {
# "name": "Alice",
# "age": 30,
# "active": true
# }
# To file
with open("output.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)Validate and format JSON online
Before parsing in Python, use the JSON Formatter to validate and inspect your JSON. For schema validation, try the JSON Schema Validator.
Frequently asked questions
What function parses JSON in Python?
json.loads(string) parses a JSON string. json.load(file_object) reads from a file. Both are in Python's built-in json module — no third-party library needed. For better performance, orjson and ujson are drop-in alternatives.
What Python type does a JSON object become?
JSON object → Python dict. JSON array → list. JSON string → str. JSON integer → int. JSON float → float. JSON true/false → True/False. JSON null → None.
What does JSON null become in Python?
JSON null becomes Python None. Check with if value is None rather than if not value, since 0, "", and [] are also falsy but semantically different from None.
How do I handle JSONDecodeError in Python?
Wrap json.loads() in try/except json.JSONDecodeError as e. The exception provides e.msg, e.lineno, and e.colno for precise error reporting. json.JSONDecodeError is a subclass of ValueError.
What is the difference between json.loads and json.load?
json.loads() (with "s") takes a string. json.load() takes a file object and reads from it directly. Use json.load(f) when reading from files — don't read the file to a string just to pass it to json.loads().
Can Python json.loads parse a list?
Yes. json.loads() parses any valid JSON including arrays, primitives, and null at the top level. A JSON array like '[1, 2, 3]' returns a Python list [1, 2, 3]. An array of objects returns a list of dicts.
Further reading and primary sources
- Python docs — json module — Official reference for json.loads, json.load, JSONDecoder, and encoder customization
- PEP 8259 / RFC 8259 — The JSON grammar Python's json module implements
- orjson — Faster JSON for Python — 2-5× faster than the stdlib json module; preferred for hot paths
- Pydantic — Data validation — Schema-based parsing of JSON into typed Python models
Recommended reading
- Fluent Python (2nd Edition) — Luciano RamalhoWrite idiomatic Python — data model, dataclasses, type hints, and clean (de)serialization patterns.
- Designing Data-Intensive Applications (2nd Edition) — Martin Kleppmann & Chris RiccominiThe modern classic on data systems — encoding formats, schemas, replication, and stream processing.
As an Amazon Associate, Jsonic earns from qualifying purchases.