JSONata in Go Package jsonata is a query and transformation language for JSON

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

Usage

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.

Comments
  • Add 'Clean' function & decimal precision [from another fork]

    Add 'Clean' function & decimal precision [from another fork]

    bit of code taken from the jsonata-test section and modified so that comments (like this one) can be written in the code enables:

    - comments in jsonata code
    - fields with any character in their name i.e 'Field #' or "$ CURRENCY"
    

    use case:

    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)
    	}
    	
    	jsonataCode := "$sum(orders.(price*quantity)) /* this is an inline comment!*/"
    	
    	cleanCode := jsonata.Clean(jsonataCode)
    
    	// Create expression.
    	e := jsonata.MustCompile(cleanCode)
    
    	// Evaluate.
    	res, err := e.Eval(data)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	fmt.Println(res)
    	// Output: 135
    }
    
  • add 'Distinct' function

    add 'Distinct' function

    This function will remove exact duplicate objects in a jsonata result. You can't always use $distinct() where you want to (only on top level calls) so this is a go 'distinct' that you can run after you've done jsonata work.

    It's a simple function but saves people having to discover this themselves.

    I figured this would be a useful function to embed in the go package - because then people can run it like this within go:

    	e := jsonata.MustCompile("$sum(orders.(price*quantity))")
    
    	// Evaluate.
    	res, err := e.Eval(data)
    	if err != nil {
    		log.Fatal(err)
    	}
    
            f, err := jsonata.Distinct(res)
    	if err != nil {
    		log.Fatal(err)
    	}
            // f will be a distinct set of results
    
  • ♻️ float to decimal & set DivisionPrecision = 8

    ♻️ float to decimal & set DivisionPrecision = 8

    Changes

    • float to decimal
    • setting DivisionPrecision = 8

    PR Type

    What kind of change does this PR introduce?

    • [ ] Bugfix
    • [ ] Feature
    • [ ] Code style update (formatting, local variables)
    • [x] Refactoring (no functional changes, no api changes)
    • [ ] Build related changes
    • [ ] CI related changes
    • [ ] Documentation content changes
    • [ ] angular.io application / infrastructure changes
    • [ ] Other... Please describe:

    Does this PR introduce a breaking change?

    • [ ] Yes
    • [x] No
  • How to resolve “does not match function signature” in jsonata.Extension

    How to resolve “does not match function signature” in jsonata.Extension

    Excuse. I have defined a jsonata.Extension, for example:

    "mandatory": { Func: func(input string) (string, error) { if input == "" { return input, errors.New(" input is required ") } return input, nil }, }

    If the parameter is not passed to “input”, how can I make jsonata not report an error?

  • Is the *Expr returned from Compile thread-safe?

    Is the *Expr returned from Compile thread-safe?

    Hi,

    First, thanks for the library. I want to cache the compiled expression and use it concurrently across threads. Is this possible?

    See this feature in the .Net version. https://github.com/mikhail-barg/jsonata.net.native

    Thanks

  • merge various branch fixes together

    merge various branch fixes together

    includes commits from https://github.com/ASJadeTech/jsonata-go and https://github.com/xiatechs/jsonata-go

    features:

    • add refactored decimal precision logic
    • add ability to include /* comments */ and ability to use $."Fields with spaces"
    • adds a simple join function 0 $sjoin(obj1, obj2, "id", "id) etc
  • add @ operator to blues jsonata

    add @ operator to blues jsonata

    Firstly - excellent work porting jsonata to Golang. Impressive. I have a request:

    In original JSONATA they have # and @ operators which enable JOIN like operations on data (a simplification on top of usage of map and filter) i.e

    $$.new.additionalfeatures @ $T1.$$.old.items @ $T2[$T1.id = $T2.id].{
        "id": $T1.id,
        "color": $T1.colour,
        "name": $T2.name
    }
    

    and currently you'd need to do something like

    $$.old.items.{
        "id": $.id,
        "name": $.name,
        "color": ($filter($$.new.additionalfeatures, function($i){$i.id = $.id})).colour
    }
    

    It would be useful to have at least the @ operator added to the Go port of jsonata.

    I appreciate this would be a fiddly bit of work - so it's a 'nice to have'.

  • $ != $[]

    $ != $[]

    In try.jsonata.org, the following evaluate identically as a way of demoting the entire source object into a field.

    { "event":$[0] }

    ...and...

    { "event":$[] }

    ...are equivalent to...

    { "event":$ }

    In jsonata-go, $[0] does what one would expect, but the others do not.

Related tags
Package json implements encoding and decoding of JSON as defined in RFC 7159

Package json implements encoding and decoding of JSON as defined in RFC 7159. The mapping between JSON and Go values is described in the documentation for the Marshal and Unmarshal functions

Jun 26, 2022
JSON Spanner - A Go package that provides a fast and simple way to filter or transform a json document

JSON SPANNER JSON Spanner is a Go package that provides a fast and simple way to

Sep 14, 2022
JSON query in Golang

gojq JSON query in Golang. Install go get -u github.com/elgs/gojq This library serves three purposes: makes parsing JSON configuration file much easie

Dec 28, 2022
Console JSON formatter with query feature
Console JSON formatter with query feature

Console JSON formatter with query feature. Install: $ go get github.com/miolini/jsonf Usage: Usage of jsonf: -c=true: colorize output -d=false: de

Dec 4, 2022
A library to query the godoc.org JSON API.

gopkg This repository provides minimal Go package that makes queries against the godoc.org JSON API. Since that site has mostly been subsumed by pkg.g

Dec 2, 2022
JSON:API compatible query string parser

QParser The package helps to parse part of the URL path and its parameters string to a handy structure. The structure format is compatible with the JS

Dec 21, 2021
Json-go - CLI to convert JSON to go and vice versa
Json-go - CLI to convert JSON to go and vice versa

Json To Go Struct CLI Install Go version 1.17 go install github.com/samit22/js

Jul 29, 2022
Get JSON values quickly - JSON parser for Go
Get JSON values quickly - JSON parser for Go

get json values quickly GJSON is a Go package that provides a fast and simple way to get values from a json document. It has features such as one line

Dec 28, 2022
JSON diff library for Go based on RFC6902 (JSON Patch)

jsondiff jsondiff is a Go package for computing the diff between two JSON documents as a series of RFC6902 (JSON Patch) operations, which is particula

Dec 4, 2022
Fast JSON encoder/decoder compatible with encoding/json for Go
Fast JSON encoder/decoder compatible with encoding/json for Go

Fast JSON encoder/decoder compatible with encoding/json for Go

Jan 6, 2023
A Go package for handling common HTTP JSON responses.

go-respond A Go package for handling common HTTP JSON responses. Installation go get github.com/nicklaw5/go-respond Usage The goal of go-respond is to

Sep 26, 2022
a Go package to interact with arbitrary JSON

go-simplejson a Go package to interact with arbitrary JSON Importing import github.com/bitly/go-simplejson Documentation Visit the docs on Go package

Dec 29, 2022
vjson is a Go package that helps to validate JSON objects in a declarative way.

vjson vjson is a Go package that helps to validate JSON objects in a declarative way. Getting Started Installing For installing vjson, use command bel

Nov 24, 2022
jsonc is a Go package that converts the jsonc format to standard json.

jsonc jsonc is a Go package that converts the jsonc format to standard json. The jsonc format is like standard json but allows for comments and traili

Nov 22, 2022
A very rudimentary JSON compare package in GO

simple_json_compare A very rudimentary JSON compare package Sample code package main import ( "fmt" "github.com/CalypsoSys/simple_json_compare" )

Oct 20, 2021
A Go package to interact with arbitrary JSON

go-simplejson a Go package to interact with arbitrary JSON Importing import github.com/bitly/go-simplejson Documentation Visit the docs on Go package

Oct 20, 2021
This is an experimental package for working with JSON-LD documents in Go

JSON-LD ?? Simple JSON-LD in Go This is an experimental package for working with JSON-LD documents in Go. Experimental, Pre-Alpha Quality Please do no

Jul 6, 2022
Fast JSON parser and validator for Go. No custom structs, no code generation, no reflection

fastjson - fast JSON parser and validator for Go Features Fast. As usual, up to 15x faster than the standard encoding/json. See benchmarks. Parses arb

Jan 5, 2023
Fast and flexible JSON encoder for Go
Fast and flexible JSON encoder for Go

Jettison Jettison is a fast and flexible JSON encoder for the Go programming language, inspired by bet365/jingo, with a richer features set, aiming at

Dec 21, 2022