Created
March 18, 2021 14:51
-
-
Save frangarcia/f43cc9139f0781f8132d10fec745ed3b to your computer and use it in GitHub Desktop.
Json logic with Groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Some example using a library with json logic | |
- https://jsonlogic.com/ | |
- https://github.com/jamsesso/json-logic-java | |
*/ | |
@GrabConfig( systemClassLoader=true ) | |
@Grapes( | |
@Grab(group='io.github.jamsesso', module='json-logic-java', version='1.0.5') | |
) | |
import io.github.jamsesso.jsonlogic.JsonLogic | |
JsonLogic jsonLogic = new JsonLogic() | |
// Set up some JSON and some data. | |
String expression = '{"*": [{"var": "x"}, 2]}' | |
Map data = ["x": 10] | |
// Evaluate the result. | |
double result = (double) jsonLogic.apply(expression, data); | |
assert result == 20.0; | |
expression = '{ "==" : [1, 1] }' | |
data = null | |
assert jsonLogic.apply(expression, data) | |
expression = '''{"and" : [ | |
{ ">" : [3,1] }, | |
{ "<" : [1,3] } | |
] }''' | |
data = null | |
assert jsonLogic.apply(expression, data) | |
expression = '''{ "var" : ["a"] }''' | |
data = ["a":1,"b":2] | |
assert 1 == jsonLogic.apply(expression, data) | |
expression = '''{ "var" : "a" }''' | |
data = ["a":1,"b":2] | |
assert 1 == jsonLogic.apply(expression, data) | |
expression = '''{"var" : 1 }''' | |
List list = ["appe", "banana", "carrot"] | |
assert "banana" == jsonLogic.apply(expression, list) | |
expression = '''{ "and" : [ | |
{"<" : [ { "var" : "temp" }, 110 ]}, | |
{"==" : [ { "var" : "pie.filling" }, "apple" ] } | |
] }''' | |
data = ["temp":100,"pie":["filling":"apple"]] | |
assert jsonLogic.apply(expression, data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment