json_path_plus 2.0.0
json_path_plus: ^2.0.0 copied to clipboard
A Dart port of JSONPath-Plus — full-featured JSONPath query engine with filter expressions, type operators, slices, and safe evaluation. Zero dependencies.
2.0.0 #
This release folds in the previously-planned 1.2.0 work: 1.2.0 was never published to pub.dev, so its changes ship here under 2.0.0.
Breaking #
JSONPath.cacheremoved — the public mutableMap<String, dynamic>is gone. The compiled-path cache is now private (_pathCache), LRU-bounded atJSONPath.cacheCapacity(512). Inspect and clear it viaJSONPath.cacheSize,JSONPath.isCached()andJSONPath.clearCache(). The old escape hatch for poking arbitrary entries into the memo is no longer available.
Features #
- RFC 9535 filter selectors — bare filter expressions
[?@.price > 10]now work without wrapping parentheses ([?(...)]still supported). Standard filter syntax no longer needs workarounds when migrating fromjson_path. match()andsearch()function extensions —match(value, pattern)returns true iff the entire string matches the regex;search(value, pattern)matches substrings. Non-string values and invalid patterns yieldfalse(never throw), per RFC 9535 §2.4.6–2.4.7.key()function —key(@)/key()returns the member key (or array index) of the current node in filters; equivalent to the JSONPath-Plus@propertymagic variable and thejson_pathpackage'skey().- Regex literals in filter expressions — JS-style
/pattern/flagsliterals are recognised and disambiguated from division by context, so@.name.match(/^a/)works as written instead of having to be rewritten as@.name.match("^a").match(),search()andString.match()accept regex objects as well as string patterns; the RFC 9535 string form keeps its full-match semantics. String.match(pattern)method in filter expressions — returns the first matching substring ornull.BuiltInFunctionexported — sandbox entries namedmatch/search/keyshadow the built-ins, enabling user-defined filter functions.- Bounded path cache — compiled paths are memoised in a private LRU instead of an unbounded public map, so long-running processes no longer grow without limit.
Fixes #
- Ordered comparisons never matched incomparable types —
<,>,<=,>=used to degrade to0 <op> 0when the two operands were not comparable, so$.items[?(@.name <= 5)]wrongly selected string-valuednamenodes (0 <= 0istrue). Mixed-type operands now yieldfalse, matching JS ('abc' <= 5isfalsevia NaN comparison) and RFC 9535 typed comparison. This also covers booleans (JSON defines no ordering for them, sotrue >= falseis nowfalse) andNaNfrom filter arithmetic (0/0 > 5), which previously compared as greater than everything.==/===/!=/!==semantics are unchanged. @rootnow actually works in filters —_filterrewrites@rootto_$_rootbut nothing ever bound that name in the sandbox, so every filter using the advertised@rootvariable threwBad state: _$_root is not defined(or silently matched nothing underignoreEvalErrors: true). It is now bound before evaluation.- Parenthesised filters containing
)]inside a string literal —toPathArrayextracted filters with a non-greedy\[(\??\(.*?\))\]regex that stopped at the first)followed by], even inside a string.$[?(@.a == "x)]y")]matched nothing. Extraction is now a balanced, quote-aware scan. - Literal property names shaped like
#Nwere clobbered by filter placeholders — any path that both contained a filter or dynamic sub-expression and referenced a literal#<digits>property resolved the property to the sub-expression ($['#0']alone worked only because the placeholder table was empty). Substitution is now marker-safe, and%is escaped so a literal#%N%property name cannot be clobbered either. toPathStringproduced malformed path strings for keys containing quotes — segments were wrapped in'...'with no escaping, sotoPathString([r'$', "a'b"])emitted$['a'b']. Escaping is now applied on the way out and mirrored on the way in throughtoPathArray, so path strings round-trip for any consumer (logs, cross-process handoff, other parsers), not just in-process.
Hardening #
SafeEvalresource limits — expressions longer than 64 KiB (SafeEval.maxExpressionLength) or nested deeper than 256 descent frames (SafeEval.maxNestingDepth) now throw aFormatExceptioninstead of overflowing the stack (~5k nesting previously crashed). Depth is counted in recursive-descent frames and chain links, so parenthesis nesting caps around 127 levels.FormatExceptionis the recoverable "reject this query" outcome; an uncaughtErroris not. Filter-expressionErrors are converted toFormatExceptionand, underignoreEvalErrors: true, swallowed as before.- Per-evaluation context instead of shared static state — six static mutable fields (
_resultType,_evalMode,_sandbox,_otherTypeCallback,_hasParentSelector,_ignoreEvalErrors) meant a re-entrantJSONPath.evaluate— for example one started from inside amatchcallback — overwrote the in-flight walk's state. State is now created per run and threaded explicitly. Not exported, so the public API is unchanged.
Maintenance #
- README's
JsonPathMatchblock documented a class that did not exist (apathsfield, apropertyfield, andfinalmarkers that the class does not use). It now mirrors the implementation field-for-field, with internal-only fields called out and the "pointer/pathStringare populated only whenresultTypeis'all'" behaviour documented. lintsdev-dependency bumped^3.0.0→^6.1.0(andtest→^1.32.0). No new diagnostics — the codebase was already clean across five minor lint versions.analysis_options.yamlmoved off the barepackage:lints/recommended.yamlfloor:always_declare_return_types,unawaited_futures,prefer_final_locals,omit_local_variable_typesandavoid_dynamic_callsare now enabled and enforced by CI'sdart analyze --fatal-infos.prefer_final_parametersandrequire_trailing_commaswere measured and rejected (210 and 206 diagnostics respectively).- CI workflow added:
dart format --set-exit-if-changed,dart analyze --fatal-infos,dart test. - pub.dev
topicstightened tojson,jsonpath,json-query,filter,expression.
Analyzer-clean (dart analyze --fatal-infos reports zero issues); 230 tests green.
1.1.0 #
- Separated
IndexExprfromMemberExpr— cleaner AST for computed property access (obj[key]vsobj.key), enabling bracket filter expressions and dynamic properties to work correctly alongside dot-notation member access. - Fixed reverse slice —
$[::-1]now correctly returns elements in reverse order with proper start/end defaults for negative step. - Fixed backtick-escaped properties —
$.book.`0`now correctly resolves literal property names. - Fixed
!@negation — standalone@replacement now uses a proper lookahead regex so!@correctly yields!_$_vfor truthiness inversion. - Fixed
typeof null— returns"null"(JSONPath-correct) instead of JS-style"undefined". - Zero failures — all 90 tests pass.
1.0.0 #
- Initial release.
- Full-featured JSONPath query engine ported from JSONPath-Plus.
- Basic path syntax: dot notation, bracket notation, wildcards, recursive descent (
..). - Filter expressions with
@property,@parent,@root,@pathand comparison operators. - Type operators:
@string(),@number(),@boolean(),@integer(),@null(),@array(),@object(),@scalar(),@other(). ~property-name operator: returns the key name instead of value.^parent selector: returns the parent of the matched node.- Array slices: Python-style
[start:end:step]. - Dynamic properties:
[(1+2)]evaluates to index 3. - Comma-separated keys:
[0,1]selects multiple indices. - Backtick-escaped properties:
`0`for literal property lookup. - Multiple result types:
value,path,pointer,parent,parentProperty,all. - Safe expression evaluator with no
dart:mirrors, noeval(), no external dependencies. - Sound null safety (Dart 3.x).