jsonata

package module
v0.0.0-...-e2c2e32 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2025 License: MIT Imports: 7 Imported by: 0

README

JSONata in Go

Package jsonata is a query and transformation language for JSON. It's a Go port of the JavaScript library JSONata.

It currently has feature parity with jsonata-js 1.5.4. As well as a most of the functions added in newer versions. You can see potentially missing functions by looking at the jsonata-js changelog.

Install

go get github.com/blues/jsonata-go

Version Management

This library provides a unified interface for managing multiple versions of JSONata implementations, similar to how the JavaScript JSONata Exerciser allows users to select different versions.

Version Management API
Core Types
  • JSONataInstance: Interface representing a specific JSONata version
  • Expression: Interface for compiled JSONata expressions
Main Functions
  • AvailableVersions() []string: Returns sorted list of available versions
  • Open(version string) (JSONataInstance, error): Opens a specific version
  • OpenLatest() (JSONataInstance, error): Opens the latest version
  • LatestVersion() string: Returns the latest version string
Version Management Usage
// List available versions
versions := jsonata.AvailableVersions()
fmt.Println("Available versions:", versions)

// Open a specific version
instance, err := jsonata.Open("v2.0.6")
if err != nil {
    log.Fatal(err)
}

// Compile an expression
expr, err := instance.Compile("$.name", false)
if err != nil {
    log.Fatal(err)
}

// Evaluate against JSON input
input := []byte(`{"name": "John Doe"}`)
result, err := expr.Evaluate(input, nil)
if err != nil {
    log.Fatal(err)
}

fmt.Println(string(result)) // Output: "John Doe"

Direct Usage (Legacy)

import (
	"encoding/json"
	"fmt"
	"log"

	jsonata "github.com/blues/jsonata-go"
)

const jsonString = `
    {
        "orders": [
            {"price": 10, "quantity": 3},
            {"price": 0.5, "quantity": 10},
            {"price": 100, "quantity": 1}
        ]
    }
`

func main() {

	var data interface{}

	// Decode JSON.
	err := json.Unmarshal([]byte(jsonString), &data)
	if err != nil {
		log.Fatal(err)
	}

	// Create expression.
	e := jsonata.MustCompile("$sum(orders.(price*quantity))")

	// Evaluate.
	res, err := e.Eval(data)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(res)
	// Output: 135
}

JSONata Server

A locally hosted version of JSONata Exerciser for testing is available here.

JSONata tests

A CLI tool for running jsonata-go against the JSONata test suite is available here.

Contributing

We love issues, fixes, and pull requests from everyone. Please run the unit-tests, staticcheck, and goimports prior to submitting your PR. By participating in this project, you agree to abide by the Blues Inc code of conduct.

For details on contributions we accept and the process for contributing, see our contribution guide.

In addition to the Go unit tests there is also a test runner that will run against the jsonata-js test suite in the jsonata-test directory. A number of these tests currently fail, but we're working towards feature parity with the jsonata-js reference implementation. Pull requests welcome!

If you would like to contribute to this library a good first issue would be to run the jsonata-test suite, and fix any of the tests not passing.

Documentation

Overview

Package jsonata provides a version management system for multiple JSONata implementations

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AvailableVersions

func AvailableVersions() []string

AvailableVersions returns a sorted list of available JSONata versions

func LatestVersion

func LatestVersion() string

LatestVersion returns the latest available version string

func RegisterVersion

func RegisterVersion(version string, factory func() JSONataInstance)

RegisterVersion registers a JSONata version implementation

Types

type Expression

type Expression interface {
	// Evaluate evaluates the expression against JSON input with optional bindings
	Evaluate(inputJSON []byte, bindings map[string]interface{}) ([]byte, error)

	// SetMaxDepth sets the maximum recursion depth
	SetMaxDepth(maxDepth int)

	// SetMaxTime sets the maximum execution time in milliseconds
	SetMaxTime(maxMs int)

	// SetMaxRange sets the maximum range size
	SetMaxRange(maxRange int)

	// Assign assigns a value to a variable in the expression's environment
	Assign(name string, value interface{})

	// RegisterFunction registers a custom function
	RegisterFunction(name string, implementation interface{}, signature string) error

	// AST returns the abstract syntax tree of the expression
	AST() interface{}

	// Errors returns any parser errors (for recovery mode)
	Errors() []error
}

Expression represents a compiled JSONata expression that can be evaluated

type JSONataInstance

type JSONataInstance interface {
	// Version returns the version string of this JSONata instance
	Version() string

	// Compile compiles a JSONata expression string into an executable Expression
	Compile(expr string, recoveryMode bool) (Expression, error)

	// Parse parses a JSONata expression into an AST
	Parse(expr string) (interface{}, error)

	// ParseWithRecovery parses with error recovery enabled
	ParseWithRecovery(expr string) (interface{}, error)

	// RegisterGlobalFunction registers a custom function globally for all expressions
	RegisterGlobalFunction(name string, implementation interface{}, signature string) error

	// SetDefaultMaxDepth sets the global default maximum recursion depth for all new expressions
	SetDefaultMaxDepth(maxDepth int)

	// SetDefaultMaxTime sets the global default maximum execution time for all new expressions (in milliseconds)
	SetDefaultMaxTime(maxMs int)

	// SetDefaultMaxRange sets the global default maximum size for range expressions for all new expressions
	SetDefaultMaxRange(maxRange int)

	// Does this JSON contain the special undefined value?
	IsUndefined(value []byte) bool

	// Make a JSONata error (generally from a user-defined function)
	MakeError(code string, message string) error
}

JSONataInstance represents a specific version of JSONata with its exported APIs

func Open

func Open(version string) (JSONataInstance, error)

Open returns a JSONata instance for the specified version

func OpenLatest

func OpenLatest() (JSONataInstance, error)

OpenLatest returns a JSONata instance for the latest available version

Directories

Path Synopsis
Package jsonata is a query and transformation language for JSON.
Package jsonata is a query and transformation language for JSON.
jlib
Package jlib implements the JSONata function library.
Package jlib implements the JSONata function library.
jparse
Package jparse converts JSONata expressions to abstract syntax trees.
Package jparse converts JSONata expressions to abstract syntax trees.
jtypes
Package jtypes (golint)
Package jtypes (golint)

Jump to

Keyboard shortcuts

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