json
import json The json module is part of Python’s standard library and provides functions for serializing Python objects to JSON-formatted strings and deserializing JSON data back into Python objects. JSON (JavaScript Object Notation) is a lightweight data interchange format widely used in web APIs, configuration files, and data exchange between systems.
Syntax
import json
Functions
json.dump()
Serializes a Python object to a JSON-formatted stream written to a file-like object.
Signature:
json.dump(obj, fp, skipkeys=False, ensure_ascii=True, indent=None, separators=None, default=None, sort_keys=False)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
obj | object | — | The Python object to serialize |
fp | file-like | — | A file object with a write() method |
skipkeys | bool | False | If True, skip keys that aren’t basic types (str, int, float, bool, None) |
ensure_ascii | bool | True | If True, escape all non-ASCII characters |
indent | int or str | None | If set, pretty-print with that indent level |
separators | tuple | None | Custom separators (item_separator, key_separator) |
default | callable | None | Function to call for objects that can’t be serialized |
sort_keys | bool | False | If True, output dictionaries sorted by key |
Returns: None — Output is written directly to fp.
Example:
import json
data = {"name": "Alice", "age": 30, "skills": ["Python", "JavaScript"]}
with open("output.json", "w") as f:
json.dump(data, f, indent=2)
# File now contains:
# {
# "name": "Alice",
# "age": 30,
# "skills": [
# "Python",
# "JavaScript"
# ]
# }
json.dumps()
Serializes a Python object to a JSON-formatted string.
Signature:
json.dumps(obj, skipkeys=False, ensure_ascii=True, indent=None, separators=None, default=None, sort_keys=False)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
obj | object | — | The Python object to serialize |
skipkeys | bool | False | If True, skip keys that aren’t basic types |
ensure_ascii | bool | True | If True, escape all non-ASCII characters |
indent | int or str | None | Pretty-print indent level |
separators | tuple | None | Custom separators (e.g., (’,’, ’:’) for compact output) |
default | callable | None | Function for unserializable objects |
sort_keys | bool | False | If True, sort dictionary keys |
Returns: str — The JSON-formatted string.
Example:
import json
data = {"name": "Alice", "age": 30, "active": True}
# Basic serialization
result = json.dumps(data)
print(result)
# {"name": "Alice", "age": 30, "active": true}
# Pretty-printed
print(json.dumps(data, indent=4))
# {
# "name": "Alice",
# "age": 30,
# "active": true
# }
# Compact output
print(json.dumps(data, separators=(',', ':')))
# {"name":"Alice","age":30,"active":true}
json.load()
Deserializes a JSON file to a Python object.
Signature:
json.load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
fp | file-like | — | A file object containing JSON |
cls | JSONDecoder | None | Custom decoder class |
object_hook | callable | None | Function called with each decoded dict |
parse_float | callable | None | Function to parse JSON float strings |
parse_int | callable | None | Function to parse JSON int strings |
parse_constant | callable | None | Function for ‘-Infinity’, ‘Infinity’, ‘NaN’ |
object_pairs_hook | callable | None | Function called with list of pairs |
Returns: The deserialized Python object (dict, list, str, int, float, bool, or None).
Example:
import json
import io
# Reading from a file
with open("data.json", "r") as f:
data = json.load(f)
print(data)
# {'name': 'Alice', 'age': 30}
# Reading from a string (using io)
json_str = '{"name": "Bob", "scores": [95, 87, 92]}'
data = json.load(io.StringIO(json_str))
print(data)
# {'name': 'Bob', 'scores': [95, 87, 92]}
json.loads()
Deserializes a JSON string (or bytes) to a Python object.
Signature:
json.loads(s, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
s | str or bytes | — | The JSON document to deserialize |
cls | JSONDecoder | None | Custom decoder class |
object_hook | callable | None | Function called with each decoded dict |
parse_float | callable | None | Function to parse JSON floats |
parse_int | callable | None | Function to parse JSON ints |
parse_constant | callable | None | Function for ‘-Infinity’, ‘Infinity’, ‘NaN’ |
object_pairs_hook | callable | None | Function called with list of pairs |
Returns: The deserialized Python object.
Example:
import json
# Basic string parsing
result = json.loads('{"name": "Alice", "age": 30}')
print(result)
# {'name': 'Alice', 'age': 30}
# Parsing bytes (Python 3.6+)
json_bytes = b'{"active": true, "count": 42}'
result = json.loads(json_bytes)
print(result)
# {'active': True, 'count': 42}
# Handling nested structures
data = json.loads('{"user": {"name": "Alice"}, "tags": ["a", "b"]}')
print(data["user"]["name"])
# Alice
Common Patterns
Working with APIs
import json
import requests
# Fetch JSON from an API
response = requests.get("https://api.example.com/data")
data = response.json() # Shorthand for json.loads(response.text)
# Send JSON to an API
payload = {"name": "Alice", "age": 30}
response = requests.post(
"https://api.example.com/submit",
data=json.dumps(payload),
headers={"Content-Type": "application/json"}
)
Round-trip serialization
import json
# Write and read back
data = {"numbers": [1, 2, 3], "nested": {"a": 1}}
# Serialize to string
json_str = json.dumps(data, sort_keys=True)
# Deserialize back
restored = json.loads(json_str)
print(data == restored) # True
Custom encoding for complex objects
import json
from datetime import datetime
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
dt = datetime(2024, 1, 15, 10, 30, 0)
result = json.dumps({"created": dt}, cls=CustomEncoder)
print(result)
# {"created": "2024-01-15T10:30:00"}
# Alternative: using default parameter
result = json.dumps({"created": dt}, default=str)
print(result)
# {"created": "2024-01-15 10:30:00"}
Errors
- json.JSONDecodeError — Raised when parsing invalid JSON (subclass of ValueError)
- TypeError — Raised when trying to serialize an unsupported type
- ValueError — Raised when allow_nan=False and NaN/Infinity is encountered
import json
# Invalid JSON
try:
json.loads("{invalid}")
except json.JSONDecodeError as e:
print(f"Parse error: {e}")
# Unsupported type
try:
json.dumps({"func": lambda x: x})
except TypeError as e:
print(f"Type error: {e}")