baml.json.from

Serializes a value to its `json` representation, honoring `baml.ToJson` overrides on classes at every depth.

Reference version

Signature

function baml.json.from<T>(value: T) -> baml.json.json throws baml.json.SerializationError

Serializes a value to its json representation, honoring baml.ToJson overrides on classes at every depth.

The json analog of string.from. Primitives, lists, and maps render to their natural json shape; a class instance becomes {"field": value}, an enum its variant name, media the tagged form. A bigint renders as a decimal string, since JSON numbers cannot carry it, and a non-finite float renders as null.

A value whose runtime class implements baml.ToJson routes through that override instead, and an override owns its whole subtree — the walk stops descending once it dispatches one. Resolution is on the value's runtime class, so an override declared in any package is honored, not just one visible to this one.

T selects nothing. It is the call site's static type and no more; every dispatch decision is made on the value in hand.

This is the caller-facing serializer, and what v.to_json() desugars to. to_json is the same walk behind an unknown parameter.

Throws

  • baml.json.SerializationError if any value in the graph has no JSON form: a uint8array (encode it explicitly with to_base64() or to_hex()), a function, a future, or any other opaque runtime object. reason names which.

Source:<builtin>/baml/ns_json/json.bamlbytes 5979–6073