kazaam.v3: gopkg.in/qntfy/kazaam.v3 Index | Examples | Files | Directories

package kazaam

import "gopkg.in/qntfy/kazaam.v3"

Package kazaam provides a simple interface for transforming arbitrary JSON in Golang.

Index

Examples

Package Files

kazaam.go spec.go util.go

Constants

const (
    // ParseError is thrown when there is a JSON parsing error
    ParseError = iota
    // RequireError is thrown when the JSON path does not exist and is required
    RequireError
    // SpecError is thrown when the kazaam specification is not properly formatted
    SpecError
)

func IsJson Uses

func IsJson(s []byte) bool

by default, kazaam does not fully validate input data. Use IsJson() if you need to confirm input is valid before transforming. Note: This operation is very slow and memory/alloc intensive relative to most transforms.

func IsJsonFast Uses

func IsJsonFast(s []byte) bool

experimental fast validation with jsonparser

type Config Uses

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

Config is used to configure a Kazaam Transformer object. Note: a manually-initialized config object (not created with `NewDefaultConfig`) will be UNAWARE of the built-in Kazaam transforms. Built-in and third-party Kazaam transforms will have to be manually registered for Kazaam to be able to transform data.

func NewDefaultConfig Uses

func NewDefaultConfig() Config

NewDefaultConfig returns a properly initialized Config object that contains required mappings for all the built-in transform types.

func (*Config) RegisterTransform Uses

func (c *Config) RegisterTransform(name string, function TransformFunc) error

RegisterTransform registers a new transform type that satisfies the TransformFunc signature within the Kazaam configuration with the provided name. This function enables end-users to create and use custom transforms within Kazaam.

Code:

// use the default config to have access to built-in kazaam transforms
kc := NewDefaultConfig()

// register the new custom transform called "copy" which supports copying the
// value of a top-level key to another top-level key
kc.RegisterTransform("copy", func(spec *transform.Config, data []byte) ([]byte, error) {
    // the internal `Spec` will contain a mapping of source and target keys
    for targetField, sourceFieldInt := range *spec.Spec {
        sourceField := sourceFieldInt.(string)
        // Note: jsonparser.Get() strips quotes from returned strings, so a real
        // transform would need handling for that. We use a Number below for simplicity.
        result, _, _, _ := jsonparser.Get(data, sourceField)
        data, _ = jsonparser.Set(data, result, targetField)
    }
    return data, nil
})

k, _ := New(`[{"operation": "copy", "spec": {"output": "input"}}]`, kc)
kazaamOut, _ := k.TransformJSONStringToString(`{"input":72}`)

fmt.Println(kazaamOut)

Output:

{"input":72,"output":72}

type Error Uses

type Error struct {
    ErrMsg  string
    ErrType int
}

Error provides an error message (ErrMsg) and integer code (ErrType) for errors thrown during the execution of a transform

func (*Error) Error Uses

func (e *Error) Error() string

Error returns a string representation of the Error

type Kazaam Uses

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

Kazaam includes internal data required for handling the transformation. A Kazaam object must be initialized using the `New` or `NewKazaam` functions.

func New Uses

func New(specString string, config Config) (*Kazaam, error)

New creates a new Kazaam instance by parsing the `spec` argument as JSON and returns a pointer to it. Thew string `spec` must be valid JSON or empty for `New` to return a Kazaam object. This function also accepts a `Config` object used for modifying the behavior of the Kazaam Transformer.

If `spec` is an empty string, the default Kazaam behavior when the Transform variants are called is to return the original data unmodified.

At initialization time, the `spec` is checked to ensure that it is valid JSON. Further, it confirms that all individual specs have a properly-specified `operation` and details are set if required. If the spec is invalid, a nil Kazaam pointer and an explanation of the error is returned. The contents of the transform specification is further validated at Transform time.

Currently, the Config object allows end users to register additional transform types to support performing custom transformations not supported by the canonical set of transforms shipped with Kazaam.

Code:

// Initialize a default Kazaam instance (i.e. same as NewKazaam(spec string))
k, _ := New(`[{"operation": "shift", "spec": {"output": "input"}}]`, NewDefaultConfig())
kazaamOut, _ := k.TransformJSONStringToString(`{"input":"input value"}`)

fmt.Println(kazaamOut)

Output:

{"output":"input value"}

func NewKazaam Uses

func NewKazaam(specString string) (*Kazaam, error)

NewKazaam creates a new Kazaam instance with a default configuration. See documentation for `New` for complete details.

Code:

k, _ := NewKazaam(`[{"operation": "shift", "spec": {"output": "input"}}]`)
kazaamOut, _ := k.TransformJSONStringToString(`{"input":"input value"}`)

fmt.Println(kazaamOut)

Output:

{"output":"input value"}

func (*Kazaam) Transform Uses

func (k *Kazaam) Transform(data []byte) ([]byte, error)

Transform makes a copy of the byte slice `data`, transforms it according to the loaded spec, and returns the new, modified byte slice.

func (*Kazaam) TransformInPlace Uses

func (k *Kazaam) TransformInPlace(data []byte) ([]byte, error)

TransformInPlace takes the byte slice `data`, transforms it according to the loaded spec, and modifies the byte slice in place.

Note: this is a destructive operation: the transformation is done in place. You must perform a deep copy of the data prior to calling TransformInPlace if the original JSON object must be retained.

func (*Kazaam) TransformJSONString Uses

func (k *Kazaam) TransformJSONString(data string) ([]byte, error)

TransformJSONString loads the JSON string, transforms it as per the spec, and returns a pointer to a transformed []byte.

This function is especially useful when one may need to extract multiple fields from the transformed JSON.

func (*Kazaam) TransformJSONStringToString Uses

func (k *Kazaam) TransformJSONStringToString(data string) (string, error)

TransformJSONStringToString loads the JSON string `data`, transforms it as per the spec, and returns the transformed JSON string.

type TransformFunc Uses

type TransformFunc func(spec *transform.Config, data []byte) ([]byte, error)

TransformFunc defines the contract that any Transform function implementation must abide by. The transform's first argument is a `kazaam.Spec` object that contains any configuration necessary for the transform. The second argument is a `[]byte` object that contains the data to be transformed.

The data object passed in should be modified in-place and returned. Where that is not possible, a new `[]byte` object should be created and returned. The function should return an error if necessary. Transforms should strive to fail gracefully whenever possible.

Directories

PathSynopsis
kazaamA simple command-line interface (CLI) for executing kazaam transforms on data from files or stdin.
transformPackage transform package contains canonical implementations of Kazaam transforms.

Package kazaam imports 7 packages (graph). Updated 2019-07-18. Refresh now. Tools for package owners.