JSONPath Script Expressions — Dynamic Evaluation
Learn about JSONPath script expressions for dynamic value computation inside paths. Understand implementation-specific scripting capabilities and limitations.
Detailed Explanation
Script Expressions in JSONPath
Script expressions allow embedding executable code inside JSONPath queries for dynamic computation. They use parentheses () to enclose an expression that is evaluated at runtime, enabling calculations and transformations that go beyond simple comparisons.
Syntax
$.array[(@.length - 1)] // last element using length
$.array[?(@.price * @.quantity > 100)] // computed condition
Accessing Array Length
One of the most common uses of script expressions is accessing the array length:
Given:
{
"queue": ["task-a", "task-b", "task-c", "task-d"]
}
$.queue[(@.length - 1)]returns"task-d"— the last element, computed dynamically based on the actual array length.$.queue[(@.length - 2)]returns"task-c"— second to last.
Computed Filters
Script expressions can perform arithmetic in filter conditions:
{
"orders": [
{ "item": "Widget", "price": 10, "quantity": 5 },
{ "item": "Gadget", "price": 25, "quantity": 3 },
{ "item": "Bolt", "price": 2, "quantity": 100 }
]
}
$.orders[?(@.price * @.quantity > 100)] returns Bolt (total = 200) — filtering based on a computed value that does not exist as a field in the data.
Implementation Differences
Script expression support varies significantly across implementations:
| Implementation | Script Support | Notes |
|---|---|---|
| Jayway (Java) | Limited | Arithmetic in filters |
| jsonpath-plus (JS) | Extensive | Full JavaScript expressions |
| Python jsonpath-ng | Limited | Basic arithmetic |
| RFC 9535 | None | Not in the standard |
Security Considerations
Script expressions can introduce security risks because they execute code. In server-side applications:
- Never allow user-provided script expressions without sanitization.
- Prefer pre-defined queries over dynamic script construction.
- Use sandboxed evaluators when script expressions are necessary.
- Validate inputs to prevent injection attacks.
When to Use Script Expressions
- Computing derived values (totals, averages) inside filters
- Accessing dynamic array positions based on length
- Complex string manipulations within queries
For most use cases, standard filter expressions with comparison operators are sufficient and more portable.
Use Case
Use script expressions for advanced scenarios like filtering orders by computed totals (price times quantity), accessing the last N elements of an array dynamically, or applying business logic within JSONPath queries that standard operators cannot express.