baml.json.to

Decodes a `json` value into `T`, honoring `baml.FromJson` overrides on the target type at every depth.

Reference version

Signature

function baml.json.to<T>(j: baml.json.json) -> T throws baml.json.DecodeError

Decodes a json value into T, honoring baml.FromJson overrides on the target type at every depth.

The decode counterpart of baml.json.from<T>: json.from serializes a T to json, json.to reads json back as a T. A type that implements baml.FromJson is constructed through its override; everything else decodes structurally, field by field, walking lists, maps, and optionals and honoring nested overrides. Resolution is on the target type T, delivered via the type-arg channel, so an override declared in any package is honored, not just one visible to this one.

T is not inert here, as it is in from<T>. Serialization dispatches on the runtime value; decoding has only the target type to go on. Supplying a wider T than you need therefore changes the result, not just the static type.

Structural decoding follows BEP-038's raw field names, so @alias and @skip have no effect. A missing optional (T?) field decodes to null, a missing required field throws, and unrecognized object keys are ignored. Bigint and bigint literal targets accept integral JSON numbers or strings containing an optional sign followed by ASCII decimal digits, using the same rules as from_string<T>.

This is the caller-facing decoder, equivalent to T.from_json(j).

Throws

  • baml.json.DecodeError if j does not fit T, or if a baml.FromJson override rejects it. Decoding an already-parsed json never re-parses, so no ParseError arises here.

Source:<builtin>/baml/ns_json/json.bamlbytes 10504–10574