Repository navigation
JSON Schema Type Checking
Evaluating untrusted or user-configured CEL expressions against dynamic JSON without static type checking means field typos (user.ag >= 18) and type mismatches (user.id == '42') only surface at runtime.
Celly.Json compiles Draft-07 / Draft 2020-12 JSON Schemas (and .NET types via .NET 10's JsonSchemaExporter) directly into Celly static type declarations with zero external dependencies.
const string schema = """
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"$defs": {
"Address": {
"type": "object",
"properties": {
"city": { "type": "string" },
"zip": { "type": "string" }
}
}
},
"properties": {
"user": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"roles": { "type": "array", "items": { "type": "string" } },
"address": { "$ref": "#/$defs/Address" }
}
}
}
}
""";
CelEnv env = JsonSchemaEnv.Create(schema);
// Valid expression passes Check()
var parsed = env.Parse("user.id == 42 && user.address.city == 'Madison'");
var check = env.Check(parsed.Ast!);
if (check.HasErrors)
{
throw new InvalidOperationException(string.Join("; ", check.Issues));
}
CelProgram program = env.Program(parsed.Ast!);
bool result = program.EvalJsonBool(jsonDoc);
// Invalid expressions are caught BEFORE runtime:
// - env.Check(env.Parse("user.address.country == 'US'").Ast!) -> HasErrors == true (undefined field)
// - env.Check(env.Parse("user.id == 'forty-two'").Ast!) -> HasErrors == true (no matching overload)To bind the entire schema to a single named variable (pairing with JsonVariableActivation):
CelEnv env = JsonSchemaEnv.CreateForVariable("order", schema);
var parsed = env.Parse("order.user.address.city == 'Madison'");On .NET 10, Celly.Json uses the built-in System.Text.Json.Schema.JsonSchemaExporter to derive a statically checked CEL environment directly from your C# DTOs:
public sealed record CustomerDto(int Id, string Name, bool Active, List<string> Roles);
public sealed record InvoiceDto(CustomerDto Customer, double Total);
// Convenience overload (camelCase JSON naming)
CelEnv env = JsonSchemaEnv.Create<InvoiceDto>();
// NativeAOT-safe overload using a System.Text.Json source-generated context:
CelEnv aotEnv = JsonSchemaEnv.Create(MyJsonContext.Default.InvoiceDto);JsonSchemaEnv.CreateForVariable<T>("invoice", ...) is also available in both reflection and JsonTypeInfo<T> overloads.
| JSON Schema Construct | CEL Type Mapping |
|---|---|
"type": "string" |
string (or timestamp / duration / bytes when MapFormats = true) |
"type": "integer" |
int (or double when CelJsonNumberHandling.AlwaysDouble) |
"type": "number" |
double |
"type": "boolean" |
bool |
"type": "null" |
null_type |
"type": ["string", "null"] |
string (single non-null type unwrapped; multi-type unions → dyn) |
"type": "array" + "items"
|
list(T) (or list(dyn) when items is omitted) |
"type": "object" + "properties"
|
Named struct with statically checked fields |
"type": "object" + "additionalProperties": { ... }
|
map(string, T) |
"$ref": "#/$defs/..." & "#/definitions/..."
|
Resolved locally with cycle detection for recursive schemas |
"allOf" |
Merges properties from all subschemas into a single struct |
"anyOf" / "oneOf"
|
Unwraps nullable single-type unions; otherwise dyn
|
"enum" / "const"
|
Infers common literal CEL type; otherwise dyn
|
By default, JsonSchemaOptions.StrictObjectProperties is true: referencing an undeclared field on an object that defines properties fails static checking unless additionalProperties is explicitly true or a subschema.
Set StrictObjectProperties = false to treat undeclared fields as dyn unless additionalProperties: false is specified:
CelEnv env = JsonSchemaEnv.Create(
schema,
schemaOptions: new JsonSchemaOptions { StrictObjectProperties = false });Enable JsonSchemaOptions.MapFormats = true to map canonical string formats to native CEL types at both compile time and runtime:
JSON Schema format
|
CEL Type | Example JSON Value |
|---|---|---|
"date-time" |
google.protobuf.Timestamp |
"2026-06-01T12:00:00Z" |
"duration" |
google.protobuf.Duration |
"3600s" |
"byte" |
bytes |
"AQID" (base64) |
var schemaOpts = new JsonSchemaOptions { MapFormats = true };
var provider = JsonSchemaTypeProvider.FromJson(schema, schemaOptions: schemaOpts);
CelEnv env = JsonSchemaEnv.Create(schema, schemaOptions: schemaOpts);
// Obtain runtime options wired with the schema's format mappings
CelJsonOptions evalOpts = provider.CreateJsonOptions();
var parsed = env.Parse("createdAt + ttl > timestamp('2026-01-01T00:00:00Z') && size(payload) == 3");
env.Check(parsed.Ast!); // passes; comparing createdAt to a plain string would fail!
bool ok = env.Program(parsed.Ast!).EvalJsonBool(doc, evalOpts);When MapFormats is false (default), CelJsonOptions.FieldFormats is null and string lookups incur zero extra checks at runtime.
Celly.Json — High-performance System.Text.Json adapter for Celly (.NET 10, NativeAOT-ready, MIT License).