A Go implementation of JsonLogic, a standard for writing complex rules as portable JSON.
This library allows you to write business logic in a JSON format that's:
- Platform independent
- Easy to read and write
- Safe to evaluate
- Portable between front-end and back-end
go get github.com/IsaacSec/go-jsonlogic
Basic usage example:
import "github.com/IsaacSec/go-jsonlogic/jsonlogic"
rules := map[string]interface{}{
"and": []interface{}{
map[string]interface{}{"<": []interface{}{1, 2}},
map[string]interface{}{">": []interface{}{1, 0}},
},
}
data := map[string]interface{}{}
result, err := jsonlogic.Apply(rules, data)
if err != nil {
// Handle error
}
// result will be true because (1 < 2) && (1 > 0)
var
: Access data values using dot notationmissing
: (WIP) Check for missing keysmissing_some
: (WIP) Check for partial missing keys
and
: Returns true if all values are truthyor
: Returns true if any value is truthy!
: Returns the logical complement of the valueif
: Conditional branching
>
,>=
,<
,<=
: Numeric comparisons+
,-
,*
,/
: (WIP) Basic arithmeticmax
,min
: (WIP) Maximum and minimum values%
: (WIP) Modulo operation
map
: (WIP) Apply logic to each item in an arrayreduce
: (WIP) Reduce array to single valuefilter
: (WIP) Select items from arrayall
,some
: (WIP) Universal/existential quantifiersmerge
:(WIP) Combine arrays
cat
: (WIP) Concatenate stringssubstr
: (WIP) Get substringin
: (WIP) Check substring/array contains
Here are some practical examples showing how to use JsonLogic rules:
// Check if a value is between 0 and 100
rules := map[string]interface{}{
"and": []interface{}{
map[string]interface{}{
">=": []interface{}{
map[string]interface{}{"var": "value"},
0,
},
},
map[string]interface{}{
"<=": []interface{}{
map[string]interface{}{"var": "value"},
100,
},
},
},
}
data := map[string]interface{}{
"value": 50,
}
// result will be true because "value" >= 0 AND "value" <= 100
result, err := jsonlogic.Apply(rules, data)
You can extend JsonLogic with custom operations:
The library provides detailed error messages for various scenarios:
- Invalid JSON syntax
- Unknown operations
- Type mismatches
- Missing required arguments
Contributions are welcome! Please feel free to submit a Pull Request.
- Clone the repository
- Install dependencies
- Run tests:
go test -v ./...
- Based on the JsonLogic specification
- Inspired by various JsonLogic implementations in other languages