Arithmetic operations in JSON elements
Some basic arithmetic operations can be applied to the JSON elements.
The following table shows arithmetic operators. a and b can
be either a constant or a JPath construct. Basic selection, query, arithmetic, and functions are
JPath constructs.
Operator | Description |
---|---|
a + b | Add |
a - b | Subtract |
a * b | Multiply |
a / b | Divide |
New in V2 a % b | Modulo |
The following table shows examples of the arithmetic operations that you can apply to JSON elements.
Example | Description | State | Expression | Result |
---|---|---|---|---|
Addition | Basic addition | { "attr1": 1, "attr2": 4 } |
/attr1 + /attr2 |
5 |
Subtraction | Basic subtraction | { "attr1": 1, "attr2": 4 } |
/attr1 - /attr2 |
-3 |
Multiplication | Basic multiplication | { "attr1": 2, "attr2": 4 } |
/attr1 * /attr2 |
8 |
Division | Basic division | { "attr1": 12, "attr2": 4 } |
/attr1 / /attr2 |
3 |
New in V2 Modulo | Basic modulo | { "attr1": 10, "attr2": 4 } |
/attr1 % /attr2 |
2 |
Parentheses | Arithmetic that uses parentheses. | { "attr1": 4, "attr2": 2 } |
(/attr1 - /attr2) * (/attr1 + /attr2) |
12 |
Arithmetic as Array Index | Uses arithmetic to compute an array index. | { "attr1": 4, "attr2": 2, "array": [ "value 1", "value 2",
"value 3", ] } |
/array[/attr1 - /attr2] |
"value 3" |
Arithmetic in Query | Uses arithmetic as part of a query. | { "attr1": 4, "attr2": 2, "array": [ { "id": 1,
"name": "Object 1" }, { "id": 2, "name": "Object 2" }, {
"id": 3, "name": "Object 3" } ] } |
/array[@id != (/attr1 - /attr2)] |
[ { "id": 1, "name": "Object 1" }, { "id": 3,
"name": "Object 3" } ] |