https://github.com/jamsesso/json-logic-java
A pure Java implementation of JsonLogic without using the Nashorn JS engine
https://github.com/jamsesso/json-logic-java
java jsonlogic
Last synced: 8 days ago
JSON representation
A pure Java implementation of JsonLogic without using the Nashorn JS engine
- Host: GitHub
- URL: https://github.com/jamsesso/json-logic-java
- Owner: jamsesso
- License: mit
- Created: 2018-08-09T01:47:20.000Z (over 7 years ago)
- Default Branch: main
- Last Pushed: 2025-09-07T16:28:05.000Z (5 months ago)
- Last Synced: 2025-09-07T18:24:55.112Z (5 months ago)
- Topics: java, jsonlogic
- Language: Java
- Size: 173 KB
- Stars: 119
- Watchers: 6
- Forks: 53
- Open Issues: 14
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# json-logic-java
This parser accepts [JsonLogic](http://jsonlogic.com) rules and executes them in Java without Nashorn.
The JsonLogic format is designed to allow you to share rules (logic) between front-end and back-end code (regardless of language difference), even to store logic along with a record in a database.
JsonLogic is documented extensively at [JsonLogic.com](http://jsonlogic.com), including examples of every [supported operation](http://jsonlogic.com/operations.html) and a place to [try out rules in your browser](http://jsonlogic.com/play.html).
## Installation
```xml
io.github.jamsesso
json-logic-java
1.1.0
```
## Examples
The public API for json-logic-java attempts to mimic the public API of the original Javascript implementation as close as possible.
For this reason, the API is loosely typed in many places.
This implementation relies on duck-typing for maps/dictionaries and arrays: if it looks and feels like an array, we treat it like an array.
```java
// Create a new JsonLogic instance. JsonLogic is thread safe.
JsonLogic jsonLogic = new JsonLogic();
// Set up some JSON and some data.
String expression = "{\"*\": [{\"var\": \"x\"}, 2]}";
Map data = new HashMap<>();
data.put("x", 10);
// Evaluate the result.
double result = (double) jsonLogic.apply(expression, data);
assert result == 20.0;
```
You can add your own operations like so:
```java
// Register an operation.
jsonLogic.addOperation("greet", (args) -> "Hello, " + args[0] + "!");
// Evaluate the result.
String result = (String) jsonLogic.apply("{\"greet\": [\"Sam\"]}", null);
assert "Hello, Sam!".equals(result);
```
There is a `truthy` static method that mimics the truthy-ness rules of Javascript:
```java
assert JsonLogic.truthy(0) == false;
assert JsonLogic.truthy(1) == true;
assert JsonLogic.truthy("") == false;
assert JsonLogic.truthy("Hello world!") == true;
// etc...
```