How to Parse JSON in Python
Python's built-in json module handles all common JSON parsing tasks with two functions: json.loads() for strings and json.load() for files. No third-party libraries required.
Parse 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.