baml.ToJson

JSON conversion with an implicit structural default.

Reference version

Signature

interface baml.ToJson

JSON conversion with an implicit structural default.

A type implements baml.ToJson to control how baml.json.from(value) renders it, the json analog of baml.ToString. Implicit implementations render primitives naturally and containers and instances structurally. An explicit implementation customizes its own json shape.

class Temp {
  celsius float
  implements baml.ToJson {
    function to_json(self) -> baml.json.json throws baml.json.SerializationError {
      { "c": baml.json.from(self.celsius), "f": baml.json.from(self.celsius * 1.8 + 32.0) }
    }
  }
}

Unlike to_string, the conversion can fail: a value with no json representation — a uint8array without an explicit encoding, a function value — throws baml.json.SerializationError.

to_json carries the structural rendering as its default body, so implements baml.ToJson {} with no override is valid and renders exactly like a non-implementor.

Source:<builtin>/baml/conversions.bamlbytes 3859–4004

Default instance methods