json

import json
Updated March 13, 2026 · Modules
json serialization stdlib encoding decoding

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:

ParameterTypeDefaultDescription
objobjectThe Python object to serialize
fpfile-likeA file object with a write() method
skipkeysboolFalseIf True, skip keys that aren’t basic types (str, int, float, bool, None)
ensure_asciiboolTrueIf True, escape all non-ASCII characters
indentint or strNoneIf set, pretty-print with that indent level
separatorstupleNoneCustom separators (item_separator, key_separator)
defaultcallableNoneFunction to call for objects that can’t be serialized
sort_keysboolFalseIf 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:

ParameterTypeDefaultDescription
objobjectThe Python object to serialize
skipkeysboolFalseIf True, skip keys that aren’t basic types
ensure_asciiboolTrueIf True, escape all non-ASCII characters
indentint or strNonePretty-print indent level
separatorstupleNoneCustom separators (e.g., (’,’, ’:’) for compact output)
defaultcallableNoneFunction for unserializable objects
sort_keysboolFalseIf 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:

ParameterTypeDefaultDescription
fpfile-likeA file object containing JSON
clsJSONDecoderNoneCustom decoder class
object_hookcallableNoneFunction called with each decoded dict
parse_floatcallableNoneFunction to parse JSON float strings
parse_intcallableNoneFunction to parse JSON int strings
parse_constantcallableNoneFunction for ‘-Infinity’, ‘Infinity’, ‘NaN’
object_pairs_hookcallableNoneFunction 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:

ParameterTypeDefaultDescription
sstr or bytesThe JSON document to deserialize
clsJSONDecoderNoneCustom decoder class
object_hookcallableNoneFunction called with each decoded dict
parse_floatcallableNoneFunction to parse JSON floats
parse_intcallableNoneFunction to parse JSON ints
parse_constantcallableNoneFunction for ‘-Infinity’, ‘Infinity’, ‘NaN’
object_pairs_hookcallableNoneFunction 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}")

See Also