JSON¶
flpit.json turns typed objects into JSON and back. Dataclasses and nested models work out of the box.
from dataclasses import dataclass
from typing import Annotated
from flpit import FlpList
from flpit.json import JIgnore, JProp, JsonConvert
@dataclass
class Person:
first_name: str
internal_id: Annotated[str, JProp("id")]
password: Annotated[str, JIgnore] = ""
person = Person("Ada", "usr-42", "secret")
raw = JsonConvert.serialize(person, Person)
assert raw == '{"firstName":"Ada","id":"usr-42"}'
people_json = """
[
{"firstName": "Ada", "id": "usr-42"},
{"firstName": "Grace", "id": "usr-43"}
]
"""
people: FlpList[Person] = FlpList.from_json(people_json, Person)
assert people.select(lambda p: p.first_name).to_list() == ["Ada", "Grace"]
- Property names are camel case by default:
first_namebecomesfirstName. JProp("id")sets an explicit JSON name,JIgnoreleaves a field out, andJIncludeexplicitly includes an underscore-prefixed field that would otherwise be skipped.FlpList.from_json(text, Person)reads a JSON array straight into aFlpList[Person]. Pass the complete target type, such aslist[Person], toJsonConvert.deserializeso nested and generic values decode against the right schema.
Options¶
JsonSerializerOptions controls naming, default values and unknown fields:
from dataclasses import dataclass
from flpit.json import JsonConvert, JsonNamingPolicy, JsonSerializerOptions
@dataclass
class Person:
first_name: str
nick_name: str = ""
ada = Person("Ada")
# Defaults: camel case, and fields that still hold their default value are left out.
assert JsonConvert.serialize(ada, Person) == '{"firstName":"Ada"}'
snake = JsonSerializerOptions(naming_policy=JsonNamingPolicy.none)
assert JsonConvert.serialize(ada, Person, snake) == '{"first_name":"Ada"}'
The other options are default_handling (include or exclude values that still hold their default) and
unknown_field_handling (allow or disallow JSON fields the model does not have).
Custom types¶
FlpList[T] fields work without any setup. Other types are added to the type registry with register_type
(stored as one JSON value) or register_collection (stored as a JSON array):
from flpit.json import register_type
class Money:
def __init__(self, cents: int) -> None:
self.cents = cents
@classmethod
def parse(cls, text: str) -> "Money":
return cls(round(float(text.removeprefix("$")) * 100))
def format(self) -> str:
return f"${self.cents / 100:.2f}"
register_type(Money, decode=Money.parse, encode=Money.format) # stored as one JSON string
@dataclass
class Invoice:
total: Money
raw = JsonConvert.serialize(Invoice(Money(1250)), Invoice)
assert raw == '{"total":"$12.50"}'
assert JsonConvert.deserialize(raw, Invoice).total.cents == 1250
When whenever is installed, its date and time types are
registered automatically and use its ISO 8601 parsing and formatting.
Large outputs¶
JsonConvert.serialize_to() writes a JSON array to a file-like stream without building the whole document in
memory first.
Backends¶
| Backend | Used when | Notes |
|---|---|---|
msgspec |
msgspec is installed (default on CPython) | fastest |
native |
msgspec is not available (PyPy, Pyodide, ...) | standard library json, no dependencies |
Both backends implement the same contract and run the same test suite. Choose one explicitly with
flpit.json.set_backend("native") or the FLPIT_JSON_BACKEND environment variable, and ask which one is active
with get_backend(). Float output can differ in exponent spelling (1e16 against 1e+16); the values are
identical.
By default, deserialization returns instances of the model you asked for. JsonSerializerOptions(native=True)
returns the generated msgspec.Struct instead: faster, but no longer your own class (msgspec backend only).
import flpit does not load the JSON support; it is loaded on first use.