insaneJSON

package module
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2023 License: BSD-3-Clause Imports: 12 Imported by: 0

README

Insane JSON

Lighting fast and simple JSON decode/encode library for GO

Key features

To be filled

Usage

    // ==== DECODE API ====
    root, err = insaneJSON.DecodeString(jsonString)        // from string
    root, err = insaneJSON.DecodeBytes(jsonBytes)          // from byte slice
    defer insaneJSON.Release(root)                         // place root back to pool 

    // ==== GET API ====
    code = root.Dig("response", "code").AsInt()            // int from objects
    body = root.Dig("response", "body").AsString()         // string from objects

    keys = []string{"items", "3", "name"} 
    thirdItemName = root.Dig(keys...).AsString()           // string from objects and array

    // ==== CHECK API ====
    isObject = root.Dig("response").IsObject()             // is value object?
    isInt = root.Dig("response", "code").IsInt()           // is value null?
    isArray = root.Dig("items").IsArray()                  // is value array?

    // ==== DELETE API ====
    root.Dig("response", "code").Suicide()                 // delete object field
    root.Dig("items", "3").Suicide()                       // delete array element
    anyDugNode.Suicide()                                   // delete any previously dug node

    // ==== MODIFY API ====
    root.Dig("response", "code").MutateToString("OK")      // convert to string
    root.Dig("items", "3").MutateToObject()                // convert to empty object

    item = `{"name":"book","weight":1000}`
    err = root.Dig("items", "3").MutateToJSON(item)        // convert to parsed JSON  

    // ==== OBJECT API ====
    response = root.Dig("response")                        // get object
    fields = response.AsFields()                           // get object fields

    for _, field = range(fields) {                         
        fmt.Println(field.AsField())                       // print all object fields 
    }

    for _, field = range(fields) {                         
        response.Dig(field.AsField()).Suicide()            // remove all fields            
    }

    for _, field = range(fields) {                         
        field.Suicide()                                    // simpler way to remove all fields
    }
    
    header="Content-Encoding: gzip"
    response.AddField("header").MutateToString(header)     // add new field and set value 

    // ==== ARRAY API ====
    items = root.Dig("items")                              // get array
    elements = items.AsArray()                             // get array elements

    for _, element = range(elements) {                     
        fmt.Println(element.AsString())                    // print all array elements    
    }

    for _, element = range(elements) {                     
        element.Suicide()                                  // remove all elements
    }

    item = `{"name":"book","weight":1000}`
    err = items.AddElement().MutateToJSON(item)            // add new element and set value 

    // ==== ENCODE API ====
    To be filled

    // ==== STRICT API ====
    items = root.Dig("items").InStrictMode()               // convert value to strict mode
    items, err = root.DigStrict("items")                   // or get strict value directly
         
    o, err = items.AsObject()                              // now value has api with error handling  
    name, err = items.Dig("5").Dig("name").AsInt           // err won't be nil since name is a string 

    // ==== POOL API ====
    root, err = insaneJSON.DecodeString(json)              // get a root from the pool and place decoded json into it 
    emptyRoot = insaneJSON.Spawn()                         // get an empty root from the pool            

    root.DecodeString(emptyRoot, anotherJson)              // reuse a root to decode another JSONs

    insaneJSON.Release(root)                               // place roots back to the pool
    insaneJSON.Release(emptyRoot)                           

Benchmarks

To be filled

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	StartNodePoolSize      = 128
	MapUseThreshold        = 16
	DisableBeautifulErrors = false // set to "true" for best performance, if you have many decode errors

	// decode errors
	ErrEmptyJSON                    = errors.New("json is empty")
	ErrUnexpectedJSONEnding         = errors.New("unexpected ending of json")
	ErrUnexpectedEndOfString        = errors.New("unexpected end of string")
	ErrUnexpectedEndOfTrue          = errors.New("unexpected end of true")
	ErrUnexpectedEndOfFalse         = errors.New("unexpected end of false")
	ErrUnexpectedEndOfNull          = errors.New("unexpected end of null")
	ErrUnexpectedEndOfObjectField   = errors.New("unexpected end of object field")
	ErrExpectedObjectField          = errors.New("expected object field")
	ErrExpectedObjectFieldSeparator = errors.New("expected object field separator")
	ErrExpectedValue                = errors.New("expected value")
	ErrExpectedComma                = errors.New("expected comma")

	// api errors
	ErrRootIsNil = errors.New("root is nil")
	ErrNotFound  = errors.New("node isn't found")
	ErrNotObject = errors.New("node isn't an object")
	ErrNotArray  = errors.New("node isn't an array")
	ErrNotBool   = errors.New("node isn't a bool")
	ErrNotString = errors.New("node isn't a string")
	ErrNotNumber = errors.New("node isn't a number")
	ErrNotField  = errors.New("node isn't an object field")
)

Functions

func Fuzz

func Fuzz(data []byte) int

func Release

func Release(root *Root)

Types

type Node

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

Node Is a building block of the decoded JSON. There is seven basic nodes:

  1. Object
  2. Array
  3. String
  4. Number
  5. True
  6. False
  7. Null

And a special one – Field, which represents the field(key) on an objects. It allows to easily change field's name, checkout MutateToField() function.

func (*Node) AddElement added in v0.0.7

func (n *Node) AddElement() *Node

func (*Node) AddElementNoAlloc added in v0.1.3

func (n *Node) AddElementNoAlloc(root *Root) *Node

func (*Node) AddField

func (n *Node) AddField(name string) *Node

func (*Node) AddFieldNoAlloc added in v0.0.14

func (n *Node) AddFieldNoAlloc(root *Root, name string) *Node

func (*Node) AppendEscapedString added in v0.1.6

func (n *Node) AppendEscapedString(out []byte) []byte

func (*Node) AsArray

func (n *Node) AsArray() []*Node

func (*Node) AsBool

func (n *Node) AsBool() bool

func (*Node) AsBytes

func (n *Node) AsBytes() []byte

func (*Node) AsEscapedString

func (n *Node) AsEscapedString() string

func (*Node) AsFieldValue

func (n *Node) AsFieldValue() *Node

func (*Node) AsFields

func (n *Node) AsFields() []*Node

func (*Node) AsFloat

func (n *Node) AsFloat() float64

func (*Node) AsInt

func (n *Node) AsInt() int

func (*Node) AsInt64 added in v0.0.20

func (n *Node) AsInt64() int64

func (*Node) AsString

func (n *Node) AsString() string

func (*Node) AsUint64 added in v0.0.20

func (n *Node) AsUint64() uint64

func (*Node) Dig

func (n *Node) Dig(path ...string) *Node

Dig legendary insane dig function

func (*Node) DigField added in v0.0.7

func (n *Node) DigField(path ...string) *Node

func (*Node) DigStrict

func (n *Node) DigStrict(path ...string) (*StrictNode, error)

func (*Node) Encode

func (n *Node) Encode(out []byte) []byte

Encode legendary insane encode function uses already created byte buffer to place json data so mem allocations may occur only if buffer isn't long enough use it for performance

func (*Node) EncodeToByte

func (n *Node) EncodeToByte() []byte

EncodeToByte legendary insane encode function slow because it allocates new byte buffer on every call use Encode to reuse already created buffer and gain more performance

func (*Node) EncodeToString

func (n *Node) EncodeToString() string

EncodeToString legendary insane encode function slow because it allocates new string on every call use Encode to reuse already created buffer and gain more performance

func (*Node) InsertElement

func (n *Node) InsertElement(pos int) *Node

func (*Node) IsArray

func (n *Node) IsArray() bool

func (*Node) IsFalse

func (n *Node) IsFalse() bool

func (*Node) IsField

func (n *Node) IsField() bool

func (*Node) IsNil

func (n *Node) IsNil() bool

func (*Node) IsNull

func (n *Node) IsNull() bool

func (*Node) IsNumber

func (n *Node) IsNumber() bool

func (*Node) IsObject

func (n *Node) IsObject() bool

func (*Node) IsString

func (n *Node) IsString() bool

func (*Node) IsTrue

func (n *Node) IsTrue() bool

func (*Node) MergeWith

func (n *Node) MergeWith(node *Node) *Node

func (*Node) MutateToArray added in v0.0.20

func (n *Node) MutateToArray() *Node

func (*Node) MutateToBool

func (n *Node) MutateToBool(value bool) *Node

func (*Node) MutateToBytes added in v0.0.20

func (n *Node) MutateToBytes(value []byte) *Node

MutateToBytes mutate to a string and use byte slice as value. It doesn't copy data, so modifications of a slice will change result JSON.

func (*Node) MutateToBytesCopy added in v0.0.20

func (n *Node) MutateToBytesCopy(root *Root, value []byte) *Node

MutateToBytes mutate to a string and use byte slice as value. It copies data, so modification of a slice won't change result JSON.

func (*Node) MutateToEscapedString

func (n *Node) MutateToEscapedString(value string) *Node

func (*Node) MutateToField

func (n *Node) MutateToField(newFieldName string) *Node

MutateToField changes name of objects's field works only with Field nodes received by AsField()/AsFields() example: root, err := insaneJSON.DecodeString(`{"a":"a","b":"b"}`) root.AsField("a").MutateToField("new_name") root.Encode() will be {"new_name":"a","b":"b"}

func (*Node) MutateToFloat

func (n *Node) MutateToFloat(value float64) *Node

func (*Node) MutateToInt

func (n *Node) MutateToInt(value int) *Node

func (*Node) MutateToInt64 added in v0.0.20

func (n *Node) MutateToInt64(value int64) *Node

func (*Node) MutateToJSON

func (n *Node) MutateToJSON(root *Root, json string) *Node

func (*Node) MutateToNode

func (n *Node) MutateToNode(node *Node) *Node

MutateToNode it isn't safe function, if you create node cycle, encode() may freeze

func (*Node) MutateToNull

func (n *Node) MutateToNull() *Node

func (*Node) MutateToObject

func (n *Node) MutateToObject() *Node

func (*Node) MutateToStrict added in v0.0.7

func (n *Node) MutateToStrict() *StrictNode

func (*Node) MutateToString

func (n *Node) MutateToString(value string) *Node

func (*Node) MutateToUint64 added in v0.0.20

func (n *Node) MutateToUint64(value uint64) *Node

func (*Node) Suicide

func (n *Node) Suicide()

Suicide legendary insane suicide function

func (*Node) TypeStr added in v0.0.7

func (n *Node) TypeStr() string

type Root

type Root struct {
	*Node
	// contains filtered or unexported fields
}

Root is a top Node of decoded JSON. It holds decoder, current JSON data and pool of Nodes. Node pool is used to reduce memory allocations and GC time. Checkout ReleaseMem()/ReleasePoolMem()/ReleaseBufMem() to clear pools. Root can be reused to decode another JSON using DecodeBytes()/DecodeString(). Also Root can decode additional JSON using DecodeAdditionalBytes()/DecodeAdditionalString().

func DecodeBytes

func DecodeBytes(jsonBytes []byte) (*Root, error)

func DecodeFile added in v0.1.4

func DecodeFile(fileName string) (*Root, error)

func DecodeString

func DecodeString(json string) (*Root, error)

func Spawn

func Spawn() *Root

func (*Root) BuffCap

func (r *Root) BuffCap() int

BuffCap returns current size of internal buffer.

func (*Root) Clear added in v0.1.5

func (r *Root) Clear()

Clear makes Root empty object

func (*Root) DecodeBytes

func (r *Root) DecodeBytes(jsonBytes []byte) error

DecodeBytes clears Root and decodes new JSON. Useful for reusing Root to reduce allocations.

func (*Root) DecodeBytesAdditional

func (r *Root) DecodeBytesAdditional(jsonBytes []byte) (*Node, error)

DecodeBytesAdditional doesn't clean Root, uses Root node pool to decode JSON

func (*Root) DecodeFile added in v0.1.4

func (r *Root) DecodeFile(fileName string) error

DecodeFile clears Root and decodes new JSON. Useful for reusing Root to reduce allocations.

func (*Root) DecodeString

func (r *Root) DecodeString(json string) error

DecodeString clears Root and decodes new JSON. Useful for reusing Root to reduce allocations.

func (*Root) DecodeStringAdditional

func (r *Root) DecodeStringAdditional(json string) (*Node, error)

DecodeStringAdditional doesn't clean Root, uses Root node pool to decode JSON

func (*Root) PoolSize added in v0.0.7

func (r *Root) PoolSize() int

PoolSize returns how many Node objects is in the pool right now.

func (*Root) ReleaseBufMem

func (r *Root) ReleaseBufMem()

ReleaseBufMem sends internal buffer to GC. Useful to reduce memory usage after decoding big JSON.

func (*Root) ReleaseMem

func (r *Root) ReleaseMem()

ReleaseMem sends node pool and internal buffer to GC. Useful to reduce memory usage after decoding big JSON.

func (*Root) ReleasePoolMem

func (r *Root) ReleasePoolMem()

ReleasePoolMem sends node pool to GC. Useful to reduce memory usage after decoding big JSON.

type StrictNode

type StrictNode struct {
	*Node
}

StrictNode implements API with error handling. Transform any Node with MutateToStrict(), Mutate*()/As*() functions will return an error

func (*StrictNode) AsArray

func (n *StrictNode) AsArray() ([]*Node, error)

func (*StrictNode) AsBool

func (n *StrictNode) AsBool() (bool, error)

func (*StrictNode) AsBytes

func (n *StrictNode) AsBytes() ([]byte, error)

func (*StrictNode) AsEscapedString

func (n *StrictNode) AsEscapedString() (string, error)

func (*StrictNode) AsFieldValue

func (n *StrictNode) AsFieldValue() (*Node, error)

func (*StrictNode) AsFields

func (n *StrictNode) AsFields() ([]*Node, error)

func (*StrictNode) AsFloat

func (n *StrictNode) AsFloat() (float64, error)

func (*StrictNode) AsInt

func (n *StrictNode) AsInt() (int, error)

func (*StrictNode) AsInt64 added in v0.0.20

func (n *StrictNode) AsInt64() (int64, error)

func (*StrictNode) AsString

func (n *StrictNode) AsString() (string, error)

func (*StrictNode) AsUint64 added in v0.0.20

func (n *StrictNode) AsUint64() (uint64, error)

Jump to

Keyboard shortcuts

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