jsonlogic

package module
v3.8.4 Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2025 License: MIT Imports: 11 Imported by: 18

README

Go JsonLogic

test workflow codecov Go Report Card

Implementation of JsonLogic in Go Lang.

What's JsonLogic?

JsonLogic is a DSL to write logic decisions in JSON. It's has a great specification and is very simple to learn. The official website has great documentation with examples.

How to use it

The use of this library is very straightforward. Here's a simple example:

package main

import (
	"bytes"
	"fmt"
	"strings"

	"github.com/diegoholiveira/jsonlogic/v3"
)

func main() {
	logic := strings.NewReader(`{"==": [1, 1]}`)
	data := strings.NewReader(`{}`)

	var result bytes.Buffer

	jsonlogic.Apply(logic, data, &result)

	fmt.Println(result.String())
}

This will output true in your console.

Here's another example, but this time using variables passed in the data parameter:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"strings"

	"github.com/diegoholiveira/jsonlogic/v3"
)

type (
	User struct {
		Name     string `json:"name"`
		Age      int    `json:"age"`
		Location string `json:"location"`
	}

	Users []User
)

func main() {
	logic := strings.NewReader(`{
        "filter": [
            {"var": "users"},
            {">=": [
                {"var": ".age"},
                18
            ]}
        ]
    }`)

	data := strings.NewReader(`{
        "users": [
            {"name": "Diego", "age": 33, "location": "Florianópolis"},
            {"name": "Jack", "age": 12, "location": "London"},
            {"name": "Pedro", "age": 19, "location": "Lisbon"},
            {"name": "Leopoldina", "age": 30, "location": "Rio de Janeiro"}
        ]
    }`)

	var result bytes.Buffer

	err := jsonlogic.Apply(logic, data, &result)
	if err != nil {
		fmt.Println(err.Error())

		return
	}

	var users Users

	decoder := json.NewDecoder(&result)
	decoder.Decode(&users)

	for _, user := range users {
		fmt.Printf("    - %s\n", user.Name)
	}
}

If you have a function you want to expose as a JsonLogic operation, you can use:

package main

import (
	"bytes"
	"fmt"
	"strings"

	"github.com/diegoholiveira/jsonlogic/v3"
)

func main() {
	// add a new operator "strlen" for get string length
	jsonlogic.AddOperator("strlen", func(values, data any) any {
		v, ok := values.(string)
		if ok {
			return len(v)
		}
		return 0
	})

	logic := strings.NewReader(`{ "strlen": { "var": "foo" } }`)
	data := strings.NewReader(`{"foo": "bar"}`)

	var result bytes.Buffer

	jsonlogic.Apply(logic, data, &result)

	fmt.Println(result.String()) // the string length of "bar" is 3
}

If you want to get the JsonLogic used, with the variables replaced by their values:

package main

import (
	"fmt"
	"encoding/json"

	"github.com/diegoholiveira/jsonlogic/v3"
)

func main() {
	logic := json.RawMessage(`{ "==":[{ "var":"foo" }, true] }`)
	data := json.RawMessage(`{"foo": "false"}`)

	result, err := jsonlogic.GetJsonLogicWithSolvedVars(logic, data)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(string(result)) // will output { "==":[false, true] }
}

License

This project is licensed under the MIT License - see LICENSE for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddOperator added in v3.2.0

func AddOperator(key string, cb OperatorFn)

AddOperator allows for custom operators to be used

func Apply

func Apply(rule, data io.Reader, result io.Writer) error

Apply reads a rule and data from `io.Reader`, applies the rule to the data and writes the result to the provided writer. It returns an error if rule processing or data handling fails.

Parameters:

  • rule: io.Reader representing the transformation rule to be applied
  • data: io.Reader containing the input data to transform
  • result: io.Writer containing the transformed data

Returns:

  • err: error if the transformation fails or if type assertions are invalid

func ApplyInterface

func ApplyInterface(rule, data any) (output any, err error)

ApplyInterface applies a transformation rule to input data using interface type assertions. It processes the input data according to the provided rule and returns the transformed result.

Parameters:

  • rule: interface{} representing the transformation rule to be applied
  • data: interface{} containing the input data to transform

Returns:

  • output: interface{} containing the transformed data
  • err: error if the transformation fails or if type assertions are invalid

func ApplyRaw

func ApplyRaw(rule, data json.RawMessage) (json.RawMessage, error)

ApplyRaw applies a validation rule to a JSON data input, both provided as raw JSON messages. It processes the input data according to the provided rule and returns the transformed result.

Parameters:

  • rule: json.RawMessage representing the transformation rule to be applied
  • data: json.RawMessage containing the input data to transform

Returns:

  • output: json.RawMessage containing the transformed data
  • err: error if the transformation fails or if type assertions are invalid

func GetJsonLogicWithSolvedVars added in v3.3.0

func GetJsonLogicWithSolvedVars(rule, data json.RawMessage) ([]byte, error)

func IsValid

func IsValid(rule io.Reader) bool

IsValid reads a JSON Logic rule from io.Reader and validates it

func ValidateJsonLogic added in v3.1.0

func ValidateJsonLogic(rules any) bool

Types

type ErrInvalidOperator

type ErrInvalidOperator struct {
	// contains filtered or unexported fields
}

func (ErrInvalidOperator) Error

func (e ErrInvalidOperator) Error() string

type ErrReduceDataType added in v3.1.0

type ErrReduceDataType struct {
	// contains filtered or unexported fields
}

func (ErrReduceDataType) Error added in v3.1.0

func (e ErrReduceDataType) Error() string

type OperatorFn added in v3.8.0

type OperatorFn func(values, data any) (result any)

Directories

Path Synopsis
javascript
Package javascript provides utilities for working with JavaScript code and runtime integration.
Package javascript provides utilities for working with JavaScript code and runtime integration.
typing
Package typing provides type checking and conversion utilities for JSON data types.
Package typing provides type checking and conversion utilities for JSON data types.

Jump to

Keyboard shortcuts

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