Skip to content

Evaluating JSON

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

Evaluating JSON

Celly.Json evaluates CEL expressions directly against System.Text.Json structures without materializing intermediate Dictionary<string, object?> or List<object?> trees.


Root Object Evaluation vs. Named Variable Binding

1. Top-Level JSON Properties as CEL Variables

When your JSON root is an object and expressions reference its fields directly (user.age >= 18):

using JsonDocument doc = JsonDocument.Parse("""{"user": {"age": 32}}""");
CelProgram program = CelEnv.Default.Compile("user.age >= 18");

bool result = program.EvalJsonBool(doc);

For hot loops, reuse a single JsonElementActivation (or JsonNodeActivation) per thread and call Reset(...) before each evaluation:

var activation = new JsonElementActivation(firstDoc.RootElement);
foreach (JsonDocument doc in incomingDocs)
{
    activation.Reset(doc.RootElement);
    bool allowed = program.Eval(activation).AsBool();
}

Both JsonElementActivation and JsonNodeActivation include an inline 4-slot lookup cache (zero array allocation) so expressions that reference the same root variable multiple times (user.age >= 18 && user.active && 'admin' in user.roles) only resolve and wrap user once.

2. Binding JSON to a Single Named Variable

When your root JSON could be any kind (object, array, primitive) or you want expressions prefixed with a variable name like payload.user.age:

var activation = new JsonVariableActivation("payload", doc.RootElement);
bool result = program.Eval(activation).AsBool();

// Reuse across requests:
activation.Reset(nextDoc.RootElement);

3. Combining JSON with Extra Variables (fallback)

Pass any IActivation (such as Celly's ValueActivation) as fallback to inject request metadata, feature flags, or timestamps alongside your JSON document:

var extra = new ValueActivation(new Dictionary<string, CelValue>
{
    ["requiredRole"] = StringValue.Of("admin"),
});

bool ok = program.EvalJsonBool(doc, fallback: extra);

4. Mixed .NET + JSON Bindings via JsonTypeAdapter

If you pass a Dictionary<string, object?> containing a mix of CLR primitives and JsonElement/JsonDocument/JsonNode values, register JsonTypeAdapter.Default on CelEnvSettings:

CelEnv env = CelEnv.Create(new CelEnvSettings
{
    Adapter = JsonTypeAdapter.Default,
});

CelProgram program = env.Compile("payload.user.name == 'Alice' && tenantId == 7");
CelValue result = program.Eval(new Dictionary<string, object?>
{
    ["payload"] = doc.RootElement,
    ["tenantId"] = 7L,
});

Configuring CelJsonOptions

CelJsonOptions is immutable and safe to share across threads.

JSON Number Semantics (CelJsonNumberHandling)

JSON has only one number type, whereas CEL strictly distinguishes int (Int64), uint (UInt64), and double. Choose the mode that fits your domain:

Mode JSON 42 JSON 42.5 JSON 18446744073709551615
Int64IfWholeElseDouble (default) int double double
PreferInt64ThenUInt64ThenDouble int double uint
AlwaysDouble double double double
var opts = new CelJsonOptions
{
    NumberHandling = CelJsonNumberHandling.PreferInt64ThenUInt64ThenDouble,
};

Case-Insensitive Property Lookup

By default, property lookup uses StringComparison.Ordinal (the fastest direct path). For case-insensitive JSON matching:

var opts = new CelJsonOptions
{
    PropertyNameComparison = StringComparison.OrdinalIgnoreCase,
};

Optional Syntax (OptionalsLibrary)

JsonElementObjectValue, JsonElementListValue, JsonNodeObjectValue, and JsonNodeListValue all support Celly's optional navigation syntax:

CelEnv env = CelEnv.Create(new CelEnvSettings
{
    EnableOptionalSyntax = true,
    Libraries = [OptionalsLibrary.Instance],
});

string role = env.Compile("user.roles[?0].orValue('guest')").EvalJsonString(doc);

JsonDocument Lifetime Safety

  • When calling program.EvalJson(JsonDocument) or program.EvalJson(JsonElement), returned object/array wrappers lazily reference the caller's JsonDocument. Keep the JsonDocument alive while reading a returned JsonElementObjectValue / JsonElementListValue, or call .Detach() if you need it to outlive the document.
  • When calling program.EvalJson(string) or program.EvalJson(ReadOnlyMemory<byte>), Celly.Json automatically detaches any JSON-backed return value before disposing the internal JsonDocument, so you will never hit ObjectDisposedException.

Low-Allocation Batch & NDJSON Streaming

Filter large JSON arrays or newline-delimited JSON (NDJSON) streams while reusing a single JsonElementActivation across every record:

CelProgram predicate = CelEnv.Default.Compile("active && score >= 85");

// Filter a JSON array of objects
foreach (JsonElement match in predicate.FilterJsonArray(arrayDoc.RootElement))
{
    Console.WriteLine(match.GetProperty("id").GetInt32());
}

// Stream NDJSON line-by-line (yields detached JsonElement clones)
foreach (JsonElement match in predicate.FilterJsonLines(utf8Stream))
{
    Console.WriteLine(match.GetRawText());
}

Clone this wiki locally