jsonlogic

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 28, 2021 License: MIT Imports: 5 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-jsonlogic

Travis CI Go Report Card Codacy Badge

Golang implementation of JsonLogic (jsonlogic.com), which is an abstract syntax tree (AST) represented as a JSON object.

Custom operators are supported.

Rules Validation is supported.

Example

var rule, data interface{}

json.Unmarshal([]byte(`
{"if": [
	{"<": [{"var":"temp"}, 0] }, "freezing",
	{"<": [{"var":"temp"}, 100] }, "liquid",
	"gas"
]}
`), &rule)

json.Unmarshal([]byte(`{"temp":55}`), &data)

got, err := jsonlogic.Apply(rule, data)
if err != nil {
	// handle error
}

fmt.Println(got)
// Output: liquid

Custom operators

You can add your own operator to jsonlogic by implementing jsonlogic.Operator interface and registering it to a jsonlogic instance.

The following example shows how to implement a greatest common divisor (gcd) operator.


// gcd operator
type gcd struct{}

// Operate implements `jsonlogic.Operator`
func (gcd) Operate(applier jsonlogic.LogicApplier, data jsonlogic.DataType, params []jsonlogic.RuleType) (jsonlogic.DataType, error) {
	if len(params) != 2 {
		return nil, errors.New("only support 2 params")
	}

	var (
		p0, p1 interface{}
		err    error
	)
	// apply jsonlogic to each parameters recursively
	if p0, err = applier.Apply(params[0], data); err != nil {
		return nil, err
	}
	if p1, err = applier.Apply(params[1], data); err != nil {
		return nil, err
	}
	p0f, ok0 := p0.(float64)
	p1f, ok1 := p1.(float64)
	if !ok0 || !ok1 {
		return nil, errors.New("params should be numbers")
	}

	// recursive GCD function
	var gcdFunc func(a int, b int) int
	gcdFunc = func(a int, b int) int {
		if b == 0 {
			return a
		}
		return gcdFunc(b, a%b)
	}
	out := gcdFunc(int(p0f), int(p1f))

	// to output a number, always use float64
	return float64(out), nil
}

// Create an instance of `jsonlogic`, and register gcd operator
jl := jsonlogic.NewJSONLogic()
jl.AddOperation("gcd", gcd{})

// Use `gcd` as an operator to calculate: gcd(14+1, 25)
var rule interface{}
json.Unmarshal([]byte(`{"gcd": [{"+": [14, 1]}, 25]}`), &rule)

got, err := jl.Apply(rule, nil)
if err != nil {
	// handle error
}

fmt.Println(got)
// Output: 5

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddOperation

func AddOperation(symbol string, op Operator) error

AddOperation to the default JSONLogic

func Apply

func Apply(rule interface{}, data interface{}) (interface{}, error)

Apply rule on data using the default JSONLogic

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/HuanTeng/go-jsonlogic"
)

func main() {
	var rule, data interface{}

	json.Unmarshal([]byte(`
{"if" : [
	{"<": [{"var":"temp"}, 0] }, "freezing",
	{"<": [{"var":"temp"}, 100] }, "liquid",
	"gas"
]}`), &rule)

	json.Unmarshal([]byte(`{"temp":55}`), &data)

	got, err := jsonlogic.Apply(rule, data)
	if err != nil {
		// handle error
	}

	fmt.Println(got)
}
Output:
liquid

func IsTrue

func IsTrue(v interface{}) bool

IsTrue converts supported interface{} into boolean

func Validate added in v0.2.0

func Validate(rule interface{}) error

Types

type DataType

type DataType interface{}

DataType is the type of data

type LogicApplier

type LogicApplier interface {
	Apply(rule interface{}, data interface{}) (interface{}, error)
	AddOperation(symbol string, op Operator) error
	Validate(rule interface{}) error
}

LogicApplier can apply logic(rule) on data, based on defined operations

func NewEmptyLogic

func NewEmptyLogic() LogicApplier

NewEmptyLogic makes an empty LogicApplier without operators

func NewJSONLogic

func NewJSONLogic() LogicApplier

NewJSONLogic makes a new LogicApplier with default jsonlogic operators

type Operator

type Operator interface {
	Operate(applier LogicApplier, data DataType, params []RuleType) (DataType, error)
}

Operator is an interface that can be added to LogicApplier

Example
package main

import (
	"encoding/json"
	"errors"
	"fmt"

	"github.com/HuanTeng/go-jsonlogic"
)

// gcd operator
type gcd struct{}

// Operate implements `jsonlogic.Operator`
func (gcd) Operate(applier jsonlogic.LogicApplier, data jsonlogic.DataType, params []jsonlogic.RuleType) (jsonlogic.DataType, error) {
	if len(params) != 2 {
		return nil, errors.New("only support 2 params")
	}

	var (
		p0, p1 interface{}
		err    error
	)
	// apply jsonlogic to each parameters recursively
	if p0, err = applier.Apply(params[0], data); err != nil {
		return nil, err
	}
	if p1, err = applier.Apply(params[1], data); err != nil {
		return nil, err
	}
	p0f, ok0 := p0.(float64)
	p1f, ok1 := p1.(float64)
	if !ok0 || !ok1 {
		return nil, errors.New("params should be numbers")
	}

	// recursive GCD function
	var gcdFunc func(a int, b int) int
	gcdFunc = func(a int, b int) int {
		if b == 0 {
			return a
		}
		return gcdFunc(b, a%b)
	}
	out := gcdFunc(int(p0f), int(p1f))

	// to output a number, always use float64
	return float64(out), nil
}

func main() {
	jl := jsonlogic.NewJSONLogic()
	jl.AddOperation("gcd", gcd{})

	var rule interface{}
	json.Unmarshal([]byte(`{"gcd": [{"+": [14, 1]}, 25]}`), &rule)

	got, err := jl.Apply(rule, nil)
	if err != nil {
		// handle error
	}

	fmt.Println(got)
}
Output:
5

type RuleType

type RuleType interface{}

RuleType is the type of rule

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL