如何为JSON Payload添加包含加减运算的JSONPath过滤条件
Got it, let's figure out how to build that filtering rule you need. The key here is that native JSONPath (per RFC 9535) doesn't support arithmetic operations directly, so you'll need to use a JSONPath implementation that extends the standard with script/expression support (like Jayway JsonPath for Java, or JSONPath Plus for JavaScript).
Core Conditions to Enforce
We need to match JSON objects where both are true:
- The
modefield equals'custom'(we'll handle case sensitivity just in case, since your example uses'CUSTOM') - The difference between
lastUpdatedDateandcreatedDateis ≥ 180000 (milliseconds, which is 3 minutes)
Working Filter Expressions by Library
1. Jayway JsonPath (Java/Scala ecosystem)
This implementation allows Groovy/JavaScript expressions in filters. Here's the expression:
$[?(@.mode.toLowerCase() == 'custom' && (@.lastUpdatedDate - @.createdDate) >= 180000)]
- If your
modevalues are strictly case-matched (only'CUSTOM'or only'custom'), you can simplify to@.mode == 'CUSTOM'instead of usingtoLowerCase(). - The arithmetic operation
@.lastUpdatedDate - @.createdDatedirectly calculates the time difference.
2. JSONPath Plus (JavaScript/browser/node.js)
This library adds support for arithmetic and more in JSONPath filters. The expression is similar:
$[?(@.mode.toLowerCase() === 'custom' && (@.lastUpdatedDate - @.createdDate) >= 180000)]
Testing with Your Example Data
Your sample JSON has:
{ "id":"1664437560", "mode":"CUSTOM", "createdDate":1664437561000, "lastUpdatedDate":1664437620256, ... }
Calculating the difference: 1664437620256 - 1664437561000 = 59256, which is less than 180000. So this object won't match the filter. If you update lastUpdatedDate to 1664437741000 (180000ms after createdDate), it will be picked up.
Why Your Earlier Sum Attempt Failed
The sum() function in JSONPath is for aggregating values across an array, not for performing arithmetic between two fields in the same object. That's why it didn't work for your use case—we need direct field-to-field subtraction, which requires extended JSONPath support.
内容的提问来源于stack exchange,提问作者om586

