Welcome to the JSON Standard Library Master Guide, a production-grade educational reference detailing JSON string parsing (json.loads), formatting (json.dumps), file I/O (json.load, json.dump), custom JSONEncoder subclassing, object_hook deserialization, unit testing via unittest, and structured learning paths for Beginner, Intermediate, and Senior developers.
- Overview & Architectural Architecture
- Python-to-JSON Type Mapping Matrix
- Developer Tier Learning Roadmap
- Directory Structure & Module Overview
- How to Run the Code
- Running Unit Tests
- Python 3.3 to 3.13 Version Evolution Matrix (with Python 2.7 Context)
- Python
range()Sequence Mechanics & Introspection (dir(range))
JSON (JavaScript Object Notation) is a lightweight, human-readable data interchange format. The Python json standard library encodes Python data structures into JSON strings and decodes JSON payloads back into native Python types.
[ Python dict / list / object ] --- json.dumps() / json.dump() ---> [ JSON String / File ]
[ JSON String / File Payload ] --- json.loads() / json.load() ---> [ Python dict / list ]
| Python Type | JSON Equivalent | Encoding Notes |
|---|---|---|
dict |
object |
Unpacked into key-value pairs (keys converted to strings) |
list, tuple |
array |
Enclosed in square brackets [...] |
str |
string |
Encoded with double quotes "..." |
int, float |
number |
Serialized as numerical literal |
True / False |
true / false |
Converted to lowercase JSON boolean literals |
None |
null |
Converted to JSON null literal |
Focuses on standard string and file JSON parsing methods:
- String Parsing:
dict_obj = json.loads(raw_str). - String Formatting:
formatted_str = json.dumps(dict_obj, indent=4). - File Read / Write:
json.dump(obj, file)andjson.load(file).
# Beginner Example: loads() and dumps()
parsed_dict = json.loads('{"title": "Python", "year": 2026}')
formatted_json = json.dumps(parsed_dict, indent=4)
print(formatted_json)Focuses on custom JSONEncoder subclassing for non-standard types (datetime, @dataclass) and sorted formatting:
- Custom JSONEncoder: Subclassing
json.JSONEncoderand overridingdefault(self, obj). - Sorted Keys & Formatting:
json.dumps(obj, cls=CustomEncoder, sort_keys=True).
# Intermediate Example: Custom JSONEncoder subclass
class CustomJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if hasattr(obj, "__dataclass_fields__"):
return asdict(obj)
return super().default(obj)Focuses on custom JSONDecoder object_hook transformations into domain classes, NDJSON (JSON-Lines) streaming, and async file I/O:
- Object Hook Deserialization:
json.loads(json_str, object_hook=user_hook). - NDJSON Streaming: Line-by-line streaming of newline-delimited JSON files.
- Async JSON I/O: Non-blocking
asynciofile reading.
# Senior Example: object_hook transformation callback
def user_object_hook(dct: dict) -> Any:
if "username" in dct and "role" in dct:
return UserRecord(username=dct["username"], role=dct["role"])
return dct
user_instance = json.loads(raw_json, object_hook=user_object_hook)json_tutorial/
βββ README.md # Master documentation and multi-tier guide
βββ test_json_tutorial.py # Multi-tier unit test suite
βββ json_processor.py # Core JSONProcessor utility wrapper class
βββ beginner_json.py # Beginner tier (loads, dumps, load, dump)
βββ intermediate_json.py # Intermediate tier (dataclasses & custom JSONEncoder)
βββ senior_json.py # Senior tier (object_hook, NDJSON streaming, async)
βββ example.py # Legacy wrapper script
βββ read_json.py # Legacy wrapper script
βββ read_stack_to_json.py # Legacy wrapper script
βββ sample.py # Legacy wrapper script
βββ data_1.txt # Sample JSON data file
βββ stack.json # Sample stack trace JSON file
βββ stack.txt # Sample text file
| File Name | Developer Tier | Key Concepts & Functions |
|---|---|---|
beginner_json.py |
π± Beginner | json.loads(), json.dumps(), json.load(), json.dump() |
intermediate_json.py |
π Intermediate | json.JSONEncoder subclassing, @dataclass, datetime ISO |
senior_json.py |
π₯ Senior | object_hook, NDJSON stream parsing, asyncio file reading |
json_processor.py |
All Tiers | JSONProcessor.parse_string(), JSONProcessor.serialize_object() |
test_json_tutorial.py |
All Tiers | unittest suite testing string/file loads, dumps, and hooks |
# Run core JSON processor
python3 json_tutorial/json_processor.py
# Run beginner tier examples
python3 json_tutorial/beginner_json.py
# Run intermediate tier examples
python3 json_tutorial/intermediate_json.py
# Run senior tier examples
python3 json_tutorial/senior_json.pyExecute unit tests via unittest or pytest:
# Run unittest suite directly
python3 -m unittest test_json_tutorial.py
# Run with pytest from repository root
pytest json_tutorial/| Python Version | JSON Engine Evolution | Syntax & System Behavior | Python 2.7 Context Comparison |
|---|---|---|---|
| Python 2.7 | json standard module introduced |
Replaced third-party simplejson library; dict.iteritems() iteration. |
json.loads() produced unicode strings u'value'. |
| Python 3.6 | Preserved dict insertion order | JSON objects encode and decode with key order preservation. | Dictionary key order was arbitrary in Python 2.7. |
| Python 3.8 | Binary JSON loads support | json.loads() accepts bytes and bytearray buffers directly. |
Required manual UTF-8 decoding json.loads(b_data.decode('utf-8')). |
| Python 3.9 | Decoder performance optimization | Accelerated json.decoder C implementation. |
Reduced string allocation overhead during large JSON parses. |
| Python 3.11 | C-accelerated JSON parser (_json) |
Faster C extension parsing for large floating-point arrays. | Significant parsing speed improvements over Python 3.6-3.10. |
| Python 3.13 | Free-threaded GIL-free CPython | High-throughput concurrent JSON encoding/decoding. | Thread-safe parallel JSON deserialization without GIL locks. |
Paging or chunking large JSON datasets frequently uses range() sequence objects:
# Chunking a list of 100 JSON records into batches of 10 using range()
json_records = [{"id": i} for i in range(100)]
batch_size = 10
for i in range(0, len(json_records), batch_size):
batch = json_records[i : i + batch_size]
print(f"Batch {i // batch_size + 1}: {len(batch)} items")-
Python 2.7 vs Python 3.x:
- In Python 2.7,
range(1_000_000)constructed an eager list of 1,000,000 integer objects in RAM (~8 MB). - In Python 3.0+,
xrange()was removed, andrange()became an immutable sequence object operating with constant$O(1)$ memory (48 bytes).
- In Python 2.7,
-
$O(1)$ Containment Testing:- Evaluating sequence containment
500 in range(0, 1000, 5)computes in constant-time arithmetic evaluation without allocating memory arrays.
- Evaluating sequence containment
Inspecting dir(range) shows standard sequence methods:
r = range(0, 10, 2)
print(r.start) # Output: 0
print(r.stop) # Output: 10
print(r.step) # Output: 2
print(r.index(6)) # Output: 3
print(r.count(4)) # Output: 1Public methods returned by dir(range):
-
start,stop,step: Range sequence boundaries. -
index(x): Returns index of element$x$ in range ($O(1)$ calculation). -
count(x): Returns count of occurrences of$x$ (0 or 1). -
__contains__(x): Evaluates membershipx in rangein$O(1)$ time.