Skip to content

Serializing CEL Results

github-actions[bot] edited this page Nov 29, 2026 · 1 revision

Serializing CEL Results

CelJsonWriter serializes any CelValue back to JSON with minimal allocations — supporting direct streaming to Utf8JsonWriter, JSON strings, UTF-8 byte arrays, and JsonNode DOM trees.


Usage

Direct Utf8JsonWriter (Zero Intermediate String Allocation)

CelValue result = program.EvalJson(doc);

using var writer = new Utf8JsonWriter(outputStream);
CelJsonWriter.Write(writer, result);
writer.Flush();

String, UTF-8 Bytes, or JsonNode

string json = result.ToJsonString();
string prettyJson = result.ToJsonString(new JsonWriterOptions { Indented = true });
byte[] utf8Bytes = result.ToUtf8JsonBytes();
JsonNode? dom = result.ToJsonNode();

CEL → JSON Type Mapping

CelJsonWriter follows Protobuf/CEL's canonical JSON representation:

CEL Type JSON Output Notes
NullValue null
BoolValue true / false
IntValue JSON number Written via WriteNumberValue(long)
UintValue JSON number Written via WriteNumberValue(ulong)
DoubleValue JSON number or string NaN → "NaN", +∞ → "Infinity", -∞ → "-Infinity"
StringValue JSON string
BytesValue Base64 JSON string Zero-alloc WriteBase64StringValue(ReadOnlySpan<byte>)
TimestampValue RFC 3339 string e.g., "2023-11-14T22:13:20Z"
DurationValue Protobuf duration string Stack-formatted Span<char>, e.g., "1.5s", "-0.25s"
EnumValue JSON integer Numeric enum value
OptionalValue Inner value or null optional.none() serializes as null
JsonElementObjectValue / JsonElementListValue Raw pass-through Uses JsonElement.WriteTo(writer) directly (zero re-encoding)
ListValue JSON array Recursively serializes elements
MapValue JSON object String, int, uint, and bool keys formatted directly
ErrorValue / UnknownValue Throws InvalidOperationException Check result.IsError first if errors are expected

Clone this wiki locally