Recipe 12.1 · Python
System.Text.Json Options Done Once
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
You serialize and deserialize JSON in a dozen places. Each call site passes its own options, or no
options at all, so one endpoint writes customerName and another writes CustomerName. Enums go
out as numbers. Reads from a partner fail because they send "42" where you expected 42. And a
profiler shows serialization taking far more time than it should.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Two problems hide here. ToJson and FromJson disagree: one writes camelCase, the other reads
with the default case-sensitive, PascalCase rules, so a round trip through this class loses every
property. And each new JsonSerializerOptions starts with an empty metadata cache. The serializer
has to reflect over your types again on every call. On a busy API that alone can cost more than
the actual work.
Requirements: Python 3.12+. Install: pip install pydantic
"""JSON helper that rebuilds serializer settings on every call
Source: ImproveCode, Chapter 12, Recipe 12.1 "System.Text.Json Options Done Once"
Section: The way it's often written
Book page: 256 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
JsonSerializerOptions -> pydantic TypeAdapter + ConfigDict built per call;
writes camelCase but reads are case-sensitive PascalCase/field names, so a
round trip silently loses data.
"""
# Not to copy: new options on every call, settings drift per call site
from typing import Any, TypeVar
from pydantic import ConfigDict, TypeAdapter
from pydantic.alias_generators import to_camel
T = TypeVar("T")
class JsonUtil:
@staticmethod
def to_json(value: Any) -> str:
options = ConfigDict(alias_generator=to_camel)
adapter: TypeAdapter[Any] = TypeAdapter(type(value), config=options)
return adapter.dump_json(value, by_alias=True).decode()
@staticmethod
def from_json(json: str, cls: type[T]) -> T:
return TypeAdapter(cls).validate_json(json) # case-sensitive
The improved recipe
Create the options once, freeze them, and share them. The listing below defines the model used in
this chapter and a JsonDefaults class with two shared instances.
A small file helper on top keeps call sites short:
Requirements: Python 3.12+. Install: pip install pydantic
"""Order, OrderLine and OrderStatus model types used by the JSON recipes
Source: ImproveCode, Chapter 12, Recipe 12.1 "System.Text.Json Options Done Once"
Section: The improved recipe
Book page: 256 -- original C# listing
Converted from C# to Python.
C# records/classes -> pydantic models (frozen, like init-only properties);
`required` members have no default; enum is a str Enum so it serializes by name.
camelCase JSON aliases live on the models (pydantic keeps naming on the type).
"""
from __future__ import annotations
import datetime as dt
from decimal import Decimal
from enum import Enum
from pydantic import BaseModel, ConfigDict, Field
from pydantic.alias_generators import to_camel
class OrderStatus(str, Enum):
PENDING = "Pending"
SHIPPED = "Shipped"
CANCELLED = "Cancelled"
class OrderLine(BaseModel):
model_config = ConfigDict(frozen=True, alias_generator=to_camel,
populate_by_name=True)
sku: str
quantity: int
unit_price: Decimal
class Order(BaseModel):
model_config = ConfigDict(frozen=True, alias_generator=to_camel,
populate_by_name=True)
id: int
customer_name: str
placed_at: dt.datetime = dt.datetime.min.replace(tzinfo=dt.timezone.utc)
status: OrderStatus = OrderStatus.PENDING
notes: str | None = None
lines: list[OrderLine] = Field(default_factory=list)
Requirements: Python 3.12+. Install: pip install pydantic
"""Shared, immutable JSON defaults: camelCase, case-insensitive reads, enums as strings
Source: ImproveCode, Chapter 12, Recipe 12.1 "System.Text.Json Options Done Once"
Section: The improved recipe
Book page: 256-257 -- original C# listing
Converted from C# to Python.
JsonSerializerOptions -> a frozen JsonOptions dataclass consumed by helper
functions built on pydantic. "Web" = camelCase out, case-insensitive in, nulls
omitted; comments and trailing commas are tolerated via a lenient pre-parse
(json5-style input is stripped of // comments and trailing commas).
"""
from __future__ import annotations
import json
import re
from dataclasses import dataclass, replace
from typing import Any, TypeVar
from pydantic import TypeAdapter
from pydantic.alias_generators import to_camel
T = TypeVar("T")
@dataclass(frozen=True)
class JsonOptions:
camel_case: bool = True
case_insensitive_reads: bool = True
ignore_nulls_when_writing: bool = True
skip_comments: bool = True
allow_trailing_commas: bool = True
enums_as_strings: bool = True
indent: int | None = None
class JsonDefaults:
# camelCase, case-insensitive reads, enums as strings.
WEB: JsonOptions = JsonOptions()
# Same as WEB, but indented for files and logs.
INDENTED: JsonOptions = replace(WEB, indent=2)
_COMMENTS = re.compile(r'("(?:\\.|[^"\\])*")|//[^\n]*|/\*.*?\*/', re.S)
_TRAILING = re.compile(r'("(?:\\.|[^"\\])*")|,(\s*[\]}])')
def _relax(text: str, options: JsonOptions) -> str:
if options.skip_comments:
text = _COMMENTS.sub(lambda m: m.group(1) or "", text)
if options.allow_trailing_commas:
text = _TRAILING.sub(lambda m: m.group(1) or m.group(2), text)
return text
def _normalize_keys(node: Any, fields: dict[str, str]) -> Any:
"""Map keys case-insensitively onto known aliases (best effort, recursive)."""
if isinstance(node, dict):
return {fields.get(k.casefold(), k): _normalize_keys(v, fields)
for k, v in node.items()}
if isinstance(node, list):
return [_normalize_keys(v, fields) for v in node]
return node
def _known_names(cls: type, seen: set[type] | None = None) -> dict[str, str]:
seen = seen or set()
names: dict[str, str] = {}
model_fields = getattr(cls, "model_fields", None)
if model_fields is None or cls in seen:
return names
seen.add(cls)
for name, info in model_fields.items():
names[name.casefold()] = name
names[to_camel(name).casefold()] = name
for arg in getattr(info.annotation, "__args__", (info.annotation,)):
names.update(_known_names(arg, seen) if isinstance(arg, type) else {})
return names
def serialize(value: Any, options: JsonOptions = JsonDefaults.WEB) -> str:
data = TypeAdapter(type(value)).dump_python(
value, mode="json", exclude_none=options.ignore_nulls_when_writing)
if options.camel_case:
data = _camelize(data)
return json.dumps(data, indent=options.indent)
def deserialize(text: str, cls: type[T],
options: JsonOptions = JsonDefaults.WEB) -> T:
data = json.loads(_relax(text, options))
if options.case_insensitive_reads:
data = _normalize_keys(data, _known_names(cls))
return TypeAdapter(cls).validate_python(data)
def _camelize(node: Any) -> Any:
if isinstance(node, dict):
return {to_camel(k): _camelize(v) for k, v in node.items()}
if isinstance(node, list):
return [_camelize(v) for v in node]
return node
Requirements: Python 3.12+. Install: pip install aiofiles
"""Read and write JSON files with the shared defaults, rejecting a JSON null
Source: ImproveCode, Chapter 12, Recipe 12.1 "System.Text.Json Options Done Once"
Section: The improved recipe
Book page: 257-258 -- original C# listing
Converted from C# to Python.
JsonSerializer.DeserializeAsync/SerializeAsync -> the serialize/deserialize
helpers from p256 over aiofiles; InvalidDataException -> ValueError subclass.
"""
from __future__ import annotations
from typing import Any, TypeVar
import aiofiles
from p256_r12_1_shared_json_defaults import JsonDefaults, deserialize, serialize
T = TypeVar("T")
class InvalidDataError(ValueError):
"""Equivalent of System.IO.InvalidDataException."""
class JsonFile:
@staticmethod
async def read_async(path: str, cls: type[T]) -> T:
async with aiofiles.open(path, encoding="utf-8") as stream:
text = await stream.read()
if text.strip() == "null":
raise InvalidDataError(f"'{path}' contained JSON null.")
return deserialize(text, cls, JsonDefaults.WEB)
@staticmethod
async def write_async(path: str, value: Any) -> None:
async with aiofiles.open(path, "w", encoding="utf-8") as stream:
await stream.write(serialize(value, JsonDefaults.INDENTED))
How it works
JsonSerializerDefaults.Web turns on the three settings almost every API wants: camelCase names,
case-insensitive property matching on read, and numbers accepted when they arrive as quoted
strings. That last one is what fixes the partner who sends "42". On top of that I skip nulls on
write, tolerate comments and trailing commas in hand-edited files, and write enums as their names.
MakeReadOnly(populateMissingResolver: true) freezes the instance and attaches the default
reflection resolver. A frozen options object can be shared across threads with no risk that some
call site changes a setting for everyone else. Any attempt to modify it throws, which is exactly
what you want to find in a code review.
The metadata cache lives on the options instance. Because Web and Indented are created once,
the serializer reflects over Order once per process, not once per call.
The Order class uses required members. Since .NET 8 the serializer honors required: if the
JSON has no id or customerName, deserialization fails with a JsonException naming the missing
property instead of handing you an object with a zero ID.
Variations and pitfalls
- Enums as strings protect stored data. If you persist JSON and someone inserts a value in the middle of an enum, every number after it now means something else. Names survive reordering.
- Coming from Newtonsoft.Json.
[JsonProperty]and[JsonIgnore]fromNewtonsoft.Jsonare silently ignored bySystem.Text.Json. Use[JsonPropertyName]and theJsonIgnorefromSystem.Text.Json.Serialization. Fields are not serialized unless you setIncludeFields, and non-public setters need[JsonInclude]. - Reference loops. Entity graphs with back references (
Order.Customer.Orders) throw by default. SetReferenceHandler = ReferenceHandler.IgnoreCycles, or better, serialize a DTO. - .NET 9 additions.
JsonSerializerOptions.Webis a ready-made frozen instance, andRespectNullableAnnotations = truemakes the serializer rejectnullfor non-nullable reference properties. Turn the second one on for new code. - Atomic writes.
JsonFile.WriteAsyncoverwrites in place. For files another process reads, write to a temporary file and move it, as shown in Chapter 10.
On .NET Framework
System.Text.Json ships as a NuGet package for .NET Framework 4.6.2 and later, and the code above
works there with the System.Text.Json package installed. If the app is already full of
Newtonsoft.Json, apply the same discipline: one static JsonSerializerSettings, created once.