jsont

package module
v0.0.0-...-9c09587 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2020 License: MIT Imports: 12 Imported by: 0

README

jsont

License MIT Go Report Card GoDoc CircleCI TODOs

Transform JSON data using .. JSON

A high performance Go library to transform JSON data using simple and easily understandable instructions written in JSON.

The transformation is performed by providing a JSON of the desired structure, but having substitution statements as leaf-level values, provided as strings. They include selectors to the input JSON document's fields and further allow for operations between various input fields. The value of an input JSON field could simply be put under a new key in the desired JSON, or be part of an operation together with other input fields.

Example

Input:

{
    "version": "1.0",
    "flight": {
        "arrivalAirport": "HAM",
        "departureAirport": "DUS",
        "economy": {
            "seats": 150,
            "wifi": true
        },
        "premiumEconomy": {
            "seats": 100,
            "wifi": true
        },
        "business": {
            "seats": 10,
            "wifi": true
        }
    }
}

Transformation description:

{
    "from": "$flight.departureAirport",
    "to": "$flight.arrivalAirport",
    "passengers": "$flight.economy.seats + $flight.premiumEconomy.seats + $flight.business.seats",
    "allWifi": "$flight.economy.wifi & $flight.premiumEconomy.wifi & $flight.business.wifi"
}

Output:

{
    "from": "DUS",
    "to": "HAM",
    "passengers": 260,
    "allWifi": true
}

Why use jsont?

The transformation of JSON data is a typical task inside of ETL (Extract, transform, load) processes. Independent of the programing language, these transformations usually result in a lot of boilerplate code: unmarshalling the input JSON on one side to set attributes of a target object and marshalling the latter into JSON again. The code for these transformations can be made much more maintainable, less error-prone and the transformation itself more extendable by giving the surrounding concerns of (un)marshalling into the hands of a library and using a declarative rather than an imperative approach to describe the transformation process. This library tries to define an easily understandable declaration language based on JSON itself, therefore completely staying in the domain of data already working with.

Installation

Using go get

Install using go get:

$ go get github.com/lucku/jsont

Install using mage (see https://www.github.com/magefile/mage)

$ git clone https://github.com/lucku/jsont
$ go get github.com/magefile/mage
$ mage install

Getting Started

CLI

jsont offers a Command Line Interface (CLI) to be used handily from the shell.

$ jsont transform -t testdata/trans1.json -o testdata testdata/input1.json
Code
jt, err := jsont.NewJSONTransformerWithFile("testdata/trans1.json")

if err != nil {
    return err
}

out, err := jt.TransformWithFile("testdata/input1.json")

if err != nil {
    return err
}

fmt.Println(out)

/* 
output: 
{
    "from": "DUS",
    "to": "HAM",
    "passengers": 260,
    "allWifi": true
}
*/

Operators

  • Arithmetic (number, number) -> number

    • Add (+)
    • Subtract (-)
    • Multiply (*)
    • Divide (/)
    • Mod (%)
    • Power (^)
    • Greater (>)
    • Greater Equal (>=)
    • Less (<)
    • Less Equal (<=)
  • Boolean (bool, bool) -> bool

    • And (&)
    • Or (|)
  • Strings (string, string) -> string

    • Concatenate (:)
  • Others

    • IfNull (?) (any, any) -> any: If the first value happens to be null, use the second one (as other operations, can be arbitrarily chained)
      • Example: "{ "name": "$aircraft.iata ? $aircraft.name" }" - if aircraft.iata is null, take aircraft.name instead
    • Equal (==) (any, any) -> bool: Returns true if the arguments are equal
      • Example: "{ "equalNames": "family.father.name == Tom" }"
    • NotEqual (!=) (any, any) -> bool: Returns true if the arguments are not equal
      • Example: "{ "equalNames": "$family.mother.numChildren != 3 }"

ToDos

  • Extend the magefile to include version information in binary
  • Provide all GoDoc comments
  • Write a full-fledged CLI
  • Support for unary operators like negation
  • Support for same operator on different data types
  • Add more operators
  • Test cases
  • Provide support for functions and implement standard function
  • Completely own implementation of JSON parsing and queries
  • Access of array elements in selector

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ExpressionEvaluator

type ExpressionEvaluator interface {
	EvaluateExpression(expr string) (*gjson.Result, error)
}

ExpressionEvaluator are low level APIs for the evaluation of expressions provided by the user inside the JSON transformation.

type JSONTransformer

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

JSONTransformer transforms JSON input data of a file into output data using a set of transformation descriptions

func NewJSONTransformer

func NewJSONTransformer(transformJSON []byte, opts ...Option) (*JSONTransformer, error)

NewJSONTransformer instantiates a new instance of a JSONTransformer struct which is used to perform the transformation of input JSON data by following instructions given in a JSON format as well. This JSON giving the transformation description has to be provided as bytes as an input to this function.

As further input, this function takes a list of options which allows certain control of the transformation behavior. See config.go for a list of configuration options.

This function returns an error if the provided transformation bytes are not valid JSON.

func NewJSONTransformerWithFile

func NewJSONTransformerWithFile(transformFile string, opts ...Option) (*JSONTransformer, error)

NewJSONTransformerWithFile instantiates a new instance of a JSONTransformer struct which is used to perform the transformation of input JSON data by following instructions given in a JSON format as well. Unlike the instantiation using NewJSONTransformer(), this function takes a filesystem path to a file that contains the JSON with transformation instructions. The path can be either relative to the execution context of the program or absolute on the system.

As further input, this function takes a list of options which allows certain control of the transformation behavior. See config.go for a list of configuration options.

This function returns an error in at least one of the following cases:

(1) the provided filesystem path is not valid

(2) the provided transformation bytes are not valid JSON

func (*JSONTransformer) Transform

func (j *JSONTransformer) Transform(inJSON []byte) ([]byte, error)

Transform takes as an input a JSON as byte array and applies the JSONTransformer's transformation description on the provided data. In case of a successful transformation, the output JSON is returned as byte array.

This function returns an error in at least one of the following cases:

(1) the provided input bytes are not valid JSON

(2) an instruction of the transformation description cannot be performed due to invalid syntax of the expression or wrong input data types

func (*JSONTransformer) TransformWithFile

func (j *JSONTransformer) TransformWithFile(inJSONFile string) ([]byte, error)

TransformWithFile takes JSON data as an input and applies the JSONTransformer's transformation description on the provided data. In case of a successful transformation, the output JSON is returned as byte array. Unlike Transform(), which accepts raw JSON bytes as input, this function takes a filesystem path to a file that contains the JSON to be transformed. The path can be either relative to the execution context of the program or absolute on the system.

This function returns an error in at least one of the following cases:

(1) the provided filesystem path is not valid

(2) the provided input bytes are not valid JSON

(3) an instruction of the transformation description cannot be performed due to invalid syntax of the expression or wrong input data types

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is a configuration option of the JSONTransformer and forms part of the functional options pattern described, e.g., in the Uber Go Style Guide: https://github.com/uber-go/guide/blob/master/style.md#functional-options

type Stack

type Stack interface {
	Push(elem interface{})
	Pop() interface{}
	Peek() interface{}
	Size() int
}

Stack is the interface for a LIFO data structure that can hold values of arbitrary type

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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