gojay

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

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

Go to latest
Published: May 21, 2018 License: MIT Imports: 10 Imported by: 0

README

Build Status codecov Go Report Card Go doc MIT License Sourcegraph stability-stable

GoJay

GoJay is a performant JSON encoder/decoder for Golang (currently the most performant, see benchmarks).

It has a simple API and doesn't use reflection. It relies on small interfaces to decode/encode structures and slices.

Gojay also comes with powerful stream decoding features and an even faster Unsafe API.

Why another JSON parser?

I looked at other fast decoder/encoder and realised it was mostly hardly readable static code generation or a lot of reflection, poor streaming features, and not so fast in the end.

Also, I wanted to build a decoder that could consume an io.Reader of line or comma delimited JSON, in a JIT way. To consume a flow of JSON objects from a TCP connection for example or from a standard output. Same way I wanted to build an encoder that could encode a flow of data to a io.Writer.

This is how GoJay aims to be a very fast, JIT stream parser with 0 reflection, low allocation with a friendly API.

Get started

go get github.com/francoispqt/gojay

Decoding

Decoding is done through two different API similar to standard encoding/json:

Example of basic stucture decoding with Unmarshal:

import "github.com/francoispqt/gojay"

type user struct {
    id int
    name string
    email string
}
// implement gojay.UnmarshalerJSONObject
func (u *user) UnmarshalJSONObject(dec *gojay.Decoder, key string) error {
    switch key {
    case "id":
        return dec.Int(&u.id)
    case "name":
        return dec.String(&u.name)
    case "email":
        return dec.String(&u.email)
    }
    return nil
}
func (u *user) NKeys() int {
    return 3
}

func main() {
    u := &user{}
    d := []byte(`{"id":1,"name":"gojay","email":"gojay@email.com"}`)
    err := gojay.UnmarshalJSONObject(d, u)
    if err != nil {
        log.Fatal(err)
    }
}

with Decode:

func main() {
    u := &user{}
    dec := gojay.NewDecoder(bytes.NewReader([]byte(`{"id":1,"name":"gojay","email":"gojay@email.com"}`)))
    err := dec.DecodeObject(d, u)
    if err != nil {
        log.Fatal(err)
    }
}
Unmarshal API

Unmarshal API decodes a []byte to a given pointer with a single function.

Behind the doors, Unmarshal API borrows a *gojay.Decoder resets its settings and decodes the data to the given pointer and releases the *gojay.Decoder to the pool when it finishes, whether it encounters an error or not.

If it cannot find the right Decoding strategy for the type of the given pointer, it returns an InvalidUnmarshalError. You can test the error returned by doing if ok := err.(InvalidUnmarshalError); ok {}.

Unmarshal API comes with three functions:

  • Unmarshal
func Unmarshal(data []byte, v interface{}) error
  • UnmarshalJSONObject
func UnmarshalJSONObject(data []byte, v gojay.UnmarshalerJSONObject) error
  • UnmarshalJSONArray
func UnmarshalJSONArray(data []byte, v gojay.UnmarshalerJSONArray) error
Decode API

Decode API decodes a []byte to a given pointer by creating or borrowing a *gojay.Decoder with an io.Reader and calling Decode methods.

Getting a *gojay.Decoder or Borrowing

You can either get a fresh *gojay.Decoder calling dec := gojay.NewDecoder(io.Reader) or borrow one from the pool by calling dec := gojay.BorrowDecoder(io.Reader).

After using a decoder, you can release it by calling dec.Release(). Beware, if you reuse the decoder after releasing it, it will panic with an error of type InvalidUsagePooledDecoderError. If you want to fully benefit from the pooling, you must release your decoders after using.

Example getting a fresh an releasing:

str := ""
dec := gojay.NewDecoder(strings.NewReader(`"test"`))
defer dec.Release()
if err := dec.Decode(&str); err != nil {
    log.Fatal(err)
}

Example borrowing a decoder and releasing:

str := ""
dec := gojay.BorrowDecoder(strings.NewReader(`"test"`))
defer dec.Release()
if err := dec.Decode(&str); err != nil {
    log.Fatal(err)
}

*gojay.Decoder has multiple methods to decode to specific types:

  • Decode
func (dec *gojay.Decoder) Decode(v interface{}) error
  • DecodeObject
func (dec *gojay.Decoder) DecodeObject(v gojay.UnmarshalerJSONObject) error
  • DecodeArray
func (dec *gojay.Decoder) DecodeArray(v gojay.UnmarshalerJSONArray) error
  • DecodeInt
func (dec *gojay.Decoder) DecodeInt(v *int) error
  • DecodeBool
func (dec *gojay.Decoder) DecodeBool(v *bool) error
  • DecodeString
func (dec *gojay.Decoder) DecodeString(v *string) error
Structs and Maps
UnmarshalerJSONObject Interface

To unmarshal a JSON object to a structure, the structure must implement the UnmarshalerJSONObject interface:

type UnmarshalerJSONObject interface {
	UnmarshalJSONObject(*gojay.Decoder, string) error
	NKeys() int
}

UnmarshalJSONObject method takes two arguments, the first one is a pointer to the Decoder (*gojay.Decoder) and the second one is the string value of the current key being parsed. If the JSON data is not an object, the UnmarshalJSONObject method will never be called.

NKeys method must return the number of keys to Unmarshal in the JSON object or 0. If zero is returned, all keys will be parsed.

Example of implementation for a struct:

type user struct {
    id int
    name string
    email string
}
// implement UnmarshalerJSONObject
func (u *user) UnmarshalJSONObject(dec *gojay.Decoder, key string) error {
    switch k {
    case "id":
        return dec.Int(&u.id)
    case "name":
        return dec.String(&u.name)
    case "email":
        return dec.String(&u.email)
    }
    return nil
}
func (u *user) NKeys() int {
    return 3
}

Example of implementation for a map[string]string:

// define our custom map type implementing UnmarshalerJSONObject
type message map[string]string

// Implementing Unmarshaler
func (m message) UnmarshalJSONObject(dec *gojay.Decoder, k string) error {
	str := ""
	err := dec.String(&str)
	if err != nil {
		return err
	}
	m[k] = str
	return nil
}

// we return 0, it tells the Decoder to decode all keys
func (m message) NKeys() int {
	return 0
}
Arrays, Slices and Channels

To unmarshal a JSON object to a slice an array or a channel, it must implement the UnmarshalerJSONArray interface:

type UnmarshalerJSONArray interface {
	UnmarshalJSONArray(*gojay.Decoder) error
}

UnmarshalJSONArray method takes one argument, a pointer to the Decoder (*gojay.Decoder). If the JSON data is not an array, the Unmarshal method will never be called.

Example of implementation with a slice:

type testSlice []string
// implement UnmarshalerJSONArray
func (t *testStringArr) UnmarshalJSONArray(dec *gojay.Decoder) error {
	str := ""
	if err := dec.String(&str); err != nil {
		return err
	}
	*t = append(*t, str)
	return nil
}

Example of implementation with a channel:

type ChannelString chan string
// implement UnmarshalerJSONArray
func (c ChannelArray) UnmarshalJSONArray(dec *gojay.Decoder) error {
	str := ""
	if err := dec.String(&str); err != nil {
		return err
	}
	c <- str
	return nil
}
Other types

To decode other types (string, int, int32, int64, uint32, uint64, float, booleans), you don't need to implement any interface.

Example of encoding strings:

func main() {
    json := []byte(`"Jay"`)
    var v string
    err := gojay.Unmarshal(json, &v)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(v) // Jay
}

Encoding

Encoding is done through two different API similar to standard encoding/json:

Example of basic structure encoding with Marshal:

import "github.com/francoispqt/gojay"

type user struct {
    id int
    name string
    email string
}
// implement MarshalerJSONObject
func (u *user) MarshalJSONObject(enc *gojay.Encoder) {
    enc.IntKey("id", u.id)
    enc.StringKey("name", u.name)
    enc.StringKey("email", u.email)
}
func (u *user) IsNil() bool {
    return u == nil
}

func main() {
    u := &user{1, "gojay", "gojay@email.com"}
    b, err := gojay.MarshalJSONObject(u)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(b)) // {"id":1,"name":"gojay","email":"gojay@email.com"}
}

with Encode:

func main() {
    func main() {
	u := &user{1, "gojay", "gojay@email.com"}
	b := strings.Builder{}
	enc := gojay.NewEncoder(&b)
	if err := enc.Encode(u); err != nil {
		log.Fatal(err)
	}
	fmt.Println(b.String()) // {"id":1,"name":"gojay","email":"gojay@email.com"}
}
Marshal API

Marshal API encodes a value to a JSON []byte with a single function.

Behind the doors, Marshal API borrows a *gojay.Encoder resets its settings and encodes the data to an internal byte buffer and releases the *gojay.Encoder to the pool when it finishes, whether it encounters an error or not.

If it cannot find the right Encoding strategy for the type of the given value, it returns an InvalidMarshalError. You can test the error returned by doing if ok := err.(InvalidMarshalError); ok {}.

Marshal API comes with three functions:

  • Marshal
func Marshal(v interface{}) ([]byte, error)
  • MarshalJSONObject
func MarshalJSONObject(v gojay.MarshalerJSONObject) ([]byte, error)
  • MarshalJSONArray
func MarshalJSONArray(v gojay.MarshalerJSONArray) ([]byte, error)
Encode API

Encode API decodes a value to JSON by creating or borrowing a *gojay.Encoder sending it to an io.Writer and calling Encode methods.

Getting a *gojay.Encoder or Borrowing

You can either get a fresh *gojay.Encoder calling enc := gojay.NewEncoder(io.Writer) or borrow one from the pool by calling enc := gojay.BorrowEncoder(io.Writer).

After using an encoder, you can release it by calling enc.Release(). Beware, if you reuse the encoder after releasing it, it will panic with an error of type InvalidUsagePooledEncoderError. If you want to fully benefit from the pooling, you must release your encoders after using.

Example getting a fresh encoder an releasing:

str := "test"
b := strings.Builder{}
enc := gojay.NewEncoder(&b)
defer enc.Release()
if err := enc.Encode(str); err != nil {
    log.Fatal(err)
}

Example borrowing an encoder and releasing:

str := "test"
b := strings.Builder{}
enc := gojay.BorrowEncoder(b)
defer enc.Release()
if err := enc.Encode(str); err != nil {
    log.Fatal(err)
}

*gojay.Encoder has multiple methods to encoder specific types to JSON:

  • Encode
func (enc *gojay.Encoder) Encode(v interface{}) error
  • EncodeObject
func (enc *gojay.Encoder) EncodeObject(v gojay.MarshalerJSONObject) error 
  • EncodeArray
func (enc *gojay.Encoder) EncodeArray(v gojay.MarshalerJSONArray) error 
  • EncodeInt
func (enc *gojay.Encoder) EncodeInt(n int) error 
  • EncodeInt64
func (enc *gojay.Encoder) EncodeInt64(n int64) error 
  • EncodeFloat
func (enc *gojay.Encoder) EncodeFloat(n float64) error
  • EncodeBool
func (enc *gojay.Encoder) EncodeBool(v bool) error
  • EncodeString
func (enc *gojay.Encoder) EncodeString(s string) error
Structs and Maps

To encode a structure, the structure must implement the MarshalerJSONObject interface:

type MarshalerJSONObject interface {
	MarshalJSONObject(enc *gojay.Encoder)
	IsNil() bool
}

MarshalJSONObject method takes one argument, a pointer to the Encoder (*gojay.Encoder). The method must add all the keys in the JSON Object by calling Decoder's methods.

IsNil method returns a boolean indicating if the interface underlying value is nil or not. It is used to safely ensure that the underlying value is not nil without using Reflection.

Example of implementation for a struct:

type user struct {
    id int
    name string
    email string
}
// implement MarshalerJSONObject
func (u *user) MarshalJSONObject(dec *gojay.Decoder, key string) {
    dec.IntKey("id", u.id)
    dec.StringKey("name", u.name)
    dec.StringKey("email", u.email)
}
func (u *user) IsNil() bool {
    return u == nil
}

Example of implementation for a map[string]string:

// define our custom map type implementing MarshalerJSONObject
type message map[string]string

// Implementing Marshaler
func (m message) MarshalJSONObject(enc *gojay.Encoder) {
	for k, v := range m {
		enc.StringKey(k, v)
	}
}

func (m message) IsNil() bool {
	return m == nil
}
Arrays and Slices

To encode an array or a slice, the slice/array must implement the MarshalerJSONArray interface:

type MarshalerJSONArray interface {
    MarshalJSONArray(enc *gojay.Encoder)
    IsNil() bool
}

MarshalJSONArray method takes one argument, a pointer to the Encoder (*gojay.Encoder). The method must add all element in the JSON Array by calling Decoder's methods.

IsNil method returns a boolean indicating if the interface underlying value is nil(empty) or not. It is used to safely ensure that the underlying value is not nil without using Reflection and also to in OmitEmpty feature.

Example of implementation:

type users []*user
// implement MarshalerJSONArray
func (u *users) MarshalJSONArray(dec *gojay.Decoder) {
	for _, e := range u {
        enc.Object(e)
    }
}
func (u *users) IsNil() bool {
    return len(u) == 0
}
Other types

To encode other types (string, int, float, booleans), you don't need to implement any interface.

Example of encoding strings:

func main() {
    name := "Jay"
    b, err := gojay.Marshal(&name)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(b)) // "Jay"
}

Stream API

Stream Decoding

GoJay ships with a powerful stream decoder.

It allows to read continuously from an io.Reader stream and do JIT decoding writing unmarshalled JSON to a channel to allow async consuming.

When using the Stream API, the Decoder implements context.Context to provide graceful cancellation.

To decode a stream of JSON, you must call gojay.Stream.DecodeStream and pass it a UnmarshalerStream implementation.

type UnmarshalerStream interface {
	UnmarshalStream(*StreamDecoder) error
}

Example of implementation of stream reading from a WebSocket connection:

// implement UnmarshalerStream
type ChannelStream chan *user

func (c ChannelStream) UnmarshalStream(dec *gojay.StreamDecoder) error {
	u := &user{}
	if err := dec.Object(u); err != nil {
		return err
	}
	c <- u
	return nil
}

func main() {
    // get our websocket connection
    origin := "http://localhost/"
    url := "ws://localhost:12345/ws"
    ws, err := websocket.Dial(url, "", origin)
    if err != nil {
        log.Fatal(err)
    }
    // create our channel which will receive our objects
    streamChan := ChannelStream(make(chan *user))
    // borrow a decoder
    dec := gojay.Stream.BorrowDecoder(ws)
    // start decoding, it will block until a JSON message is decoded from the WebSocket
    // or until Done channel is closed
    go dec.DecodeStream(streamChan)
    for {
        select {
        case v := <-streamChan:
            // Got something from my websocket!
        case <-dec.Done():
            os.Exit("finished reading from WebSocket")
        }
    }
}
Stream Encoding

GoJay ships with a powerful stream encoder part of the Stream API.

It allows to write continuously to an io.Writer and do JIT encoding of data fed to a channel to allow async consuming. You can set multiple consumers on the channel to be as performant as possible. Consumers are non blocking and are scheduled individually in their own go routine.

When using the Stream API, the Encoder implements context.Context to provide graceful cancellation.

To encode a stream of data, you must call EncodeStream and pass it a MarshalerStream implementation.

type MarshalerStream interface {
	MarshalStream(enc *gojay.StreamEncoder)
}

Example of implementation of stream writing to a WebSocket:

// Our structure which will be pushed to our stream
type user struct {
    id int
    name string
    email string
}

func (u *user) MarshalJSONObject(enc *gojay.Encoder) {
	enc.IntKey("id", u.id)
	enc.StringKey("name", u.name)
	enc.StringKey("email", u.email)
}
func (u *user) IsNil() bool {
	return u == nil
}

// Our MarshalerStream implementation
type StreamChan chan *user

func (s StreamChan) MarshalStream(enc *gojay.StreamEncoder) {
	select {
	case <-enc.Done():
		return
	case o := <-s:
		enc.Object(o)
	}
}

// Our main function
func main() {
    // get our websocket connection
    origin := "http://localhost/"
    url := "ws://localhost:12345/ws"
    ws, err := websocket.Dial(url, "", origin)
    if err != nil {
        log.Fatal(err)
    }
    // we borrow an encoder set stdout as the writer, 
    // set the number of consumer to 10
    // and tell the encoder to separate each encoded element 
    // added to the channel by a new line character
    enc := gojay.Stream.BorrowEncoder(ws).NConsumer(10).LineDelimited()
    // instantiate our MarshalerStream
    s := StreamChan(make(chan *user))
    // start the stream encoder
    // will block its goroutine until enc.Cancel(error) is called
    // or until something is written to the channel
    go enc.EncodeStream(s)
    // write to our MarshalerStream
    for i := 0; i < 1000; i++ {
        s<-&user{i,"username","user@email.com"}
    }
    // Wait
    <-enc.Done()
}

Unsafe API

Unsafe API has the same functions than the regular API, it only has Unmarshal API for now. It is unsafe because it makes assumptions on the quality of the given JSON.

If you are not sure if your JSON is valid, don't use the Unsafe API.

Also, the Unsafe API does not copy the buffer when using Unmarshal API, which, in case of string decoding, can lead to data corruption if a byte buffer is reused. Using the Decode API makes Unsafe API safer as the io.Reader relies on copy builtin method and Decoder will have its own internal buffer :)

Access the Unsafe API this way:

gojay.Unsafe.Unmarshal(b, v) 

Benchmarks

Benchmarks encode and decode three different data based on size (small, medium, large).

To run benchmark for decoder:

cd $GOPATH/src/github.com/francoispqt/gojay/benchmarks/decoder && make bench

To run benchmark for encoder:

cd $GOPATH/src/github.com/francoispqt/gojay/benchmarks/encoder && make bench

Benchmark Results

Decode

Small Payload

benchmark code is here

benchmark data is here

ns/op bytes/op allocs/op
Std Library 2547 496 4
JsonIter 2046 312 12
JsonParser 1408 0 0
EasyJson 929 240 2
GoJay 807 256 2
GoJay-unsafe 712 112 1
Medium Payload

benchmark code is here

benchmark data is here

ns/op bytes/op allocs/op
Std Library 30148 2152 496
JsonIter 16309 2976 80
JsonParser 7793 0 0
EasyJson 7957 232 6
GoJay 4984 2448 8
GoJay-unsafe 4809 144 7
Large Payload

benchmark code is here

benchmark data is here

ns/op bytes/op allocs/op
JsonIter 210078 41712 1136
EasyJson 106626 160 2
JsonParser 66813 0 0
GoJay 52153 31241 77
GoJay-unsafe 48277 2561 76

Encode

Small Struct

benchmark code is here

benchmark data is here

ns/op bytes/op allocs/op
Std Library 1280 464 3
EasyJson 871 944 6
JsonIter 866 272 3
GoJay 543 112 1
GoJay-func 347 0 0
Medium Struct

benchmark code is here

benchmark data is here

ns/op bytes/op allocs/op
Std Library 5006 1496 25
JsonIter 2232 1544 20
EasyJson 1997 1544 19
GoJay 1522 312 14
Large Struct

benchmark code is here

benchmark data is here

ns/op bytes/op allocs/op
Std Library 66441 20576 332
JsonIter 35247 20255 328
EasyJson 32053 15474 327
GoJay 27847 9802 318

Contributing

Contributions are welcome :)

If you encounter issues please report it in Github and/or send an email at francois@parquet.ninja

Documentation

Overview

Package gojay Package 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.

It aims at performance and usability by relying on simple interfaces to decode or encode structures, slices, arrays and even channels.

Index

Constants

This section is empty.

Variables

View Source
var Stream = stream{}

Stream is a struct holding the Stream api

View Source
var Unsafe = decUnsafe{}

Unsafe is the structure holding the unsafe version of the API. The difference between unsafe api and regular api is that the regular API copies the buffer passed to Unmarshal functions to a new internal buffer. Making it safer because internally GoJay uses unsafe.Pointer to transform slice of bytes into a string.

Functions

func Marshal

func Marshal(v interface{}) ([]byte, error)

Marshal returns the JSON encoding of v.

Marshal takes interface v and encodes it according to its type. Basic example with a string:

b, err := gojay.Marshal("test")
fmt.Println(b) // "test"

If v implements Marshaler or Marshaler interface it will call the corresponding methods.

If a struct, slice, or array is passed and does not implement these interfaces it will return a a non nil InvalidUnmarshalError error. Example with an Marshaler:

type TestStruct struct {
	id int
}
func (s *TestStruct) MarshalJSONObject(enc *gojay.Encoder) {
	enc.AddIntKey("id", s.id)
}
func (s *TestStruct) IsNil() bool {
	return s == nil
}

func main() {
	test := &TestStruct{
		id: 123456,
	}
	b, _ := gojay.Marshal(test)
	fmt.Println(b) // {"id":123456}
}

func MarshalJSONArray

func MarshalJSONArray(v MarshalerJSONArray) ([]byte, error)

MarshalJSONArray returns the JSON encoding of v.

It takes an array or a slice implementing Marshaler to a JSON slice of byte it returns a slice of bytes and an error. Example with an Marshaler:

type TestSlice []*TestStruct

func (t TestSlice) MarshalJSONArray(enc *Encoder) {
	for _, e := range t {
		enc.AddObject(e)
	}
}

func main() {
	test := &TestSlice{
		&TestStruct{123456},
		&TestStruct{7890},
	}
	b, _ := Marshal(test)
	fmt.Println(b) // [{"id":123456},{"id":7890}]
}

func MarshalJSONObject

func MarshalJSONObject(v MarshalerJSONObject) ([]byte, error)

MarshalJSONObject returns the JSON encoding of v.

It takes a struct implementing Marshaler to a JSON slice of byte it returns a slice of bytes and an error. Example with an Marshaler:

type TestStruct struct {
	id int
}
func (s *TestStruct) MarshalJSONObject(enc *gojay.Encoder) {
	enc.AddIntKey("id", s.id)
}
func (s *TestStruct) IsNil() bool {
	return s == nil
}

func main() {
	test := &TestStruct{
		id: 123456,
	}
	b, _ := gojay.Marshal(test)
	fmt.Println(b) // {"id":123456}
}

func Unmarshal

func Unmarshal(data []byte, v interface{}) error

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil, not a pointer, or not an implementation of UnmarshalerJSONObject or UnmarshalerJSONArray Unmarshal returns an InvalidUnmarshalError.

Unmarshal uses the inverse of the encodings that Marshal uses, allocating maps, slices, and pointers as necessary, with the following additional rules: To unmarshal JSON into a pointer, Unmarshal first handles the case of the JSON being the JSON literal null. In that case, Unmarshal sets the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into the value pointed at by the pointer. If the pointer is nil, Unmarshal allocates a new value for it to point to.

To Unmarshal JSON into a struct, Unmarshal requires the struct to implement UnmarshalerJSONObject.

To unmarshal a JSON array into a slice, Unmarshal requires the slice to implement UnmarshalerJSONArray.

Unmarshal JSON does not allow yet to unmarshall an interface value If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, Unmarshal skips that field and completes the unmarshaling as best it can. If no more serious errors are encountered, Unmarshal returns an UnmarshalTypeError describing the earliest such error. In any case, it's not guaranteed that all the remaining fields following the problematic one will be unmarshaled into the target object.

func UnmarshalJSONArray

func UnmarshalJSONArray(data []byte, v UnmarshalerJSONArray) error

UnmarshalJSONArray parses the JSON-encoded data and stores the result in the value pointed to by v.

v must implement UnmarshalerJSONArray.

If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, UnmarshalJSONArray skips that field and completes the unmarshaling as best it can.

func UnmarshalJSONObject

func UnmarshalJSONObject(data []byte, v UnmarshalerJSONObject) error

UnmarshalJSONObject parses the JSON-encoded data and stores the result in the value pointed to by v.

v must implement UnmarshalerJSONObject.

If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, UnmarshalJSONObject skips that field and completes the unmarshaling as best it can.

Types

type DecodeObjectFunc

type DecodeObjectFunc func(*Decoder, string) error

DecodeObjectFunc is a custom func type implementing UnarshaleObject. Use it to cast a func(*Decoder) to Unmarshal an object.

str := ""
dec := gojay.NewDecoder(io.Reader)
dec.DecodeObject(gojay.DecodeObjectFunc(func(dec *gojay.Decoder, k string) error {
	return dec.AddString(&str)
}))

func (DecodeObjectFunc) NKeys

func (f DecodeObjectFunc) NKeys() int

NKeys implements UnarshalerObject.

func (DecodeObjectFunc) UnmarshalJSONObject

func (f DecodeObjectFunc) UnmarshalJSONObject(dec *Decoder, k string) error

UnmarshalJSONObject implements UnarshalerObject.

type Decoder

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

A Decoder reads and decodes JSON values from an input stream.

func BorrowDecoder

func BorrowDecoder(r io.Reader) *Decoder

BorrowDecoder borrows a Decoder from the pool. It takes an io.Reader implementation as data input. It initiates the done channel returned by Done().

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder. It takes an io.Reader implementation as data input.

func (*Decoder) AddArray

func (dec *Decoder) AddArray(v UnmarshalerJSONArray) error

AddArray decodes the next key to a UnmarshalerJSONArray.

func (*Decoder) AddBool

func (dec *Decoder) AddBool(v *bool) error

AddBool decodes the next key to a *bool. If next key is neither null nor a JSON boolean, an InvalidUnmarshalError will be returned. If next key is null, bool will be false.

func (*Decoder) AddEmbeddedJSON

func (dec *Decoder) AddEmbeddedJSON(v *EmbeddedJSON) error

AddEmbeddedJSON adds an EmbeddedsJSON to the value pointed by v. It can be used to delay JSON decoding or precompute a JSON encoding.

func (*Decoder) AddFloat

func (dec *Decoder) AddFloat(v *float64) error

AddFloat decodes the next key to a *float64. If next key value overflows float64, an InvalidUnmarshalError error will be returned.

func (*Decoder) AddFloat32

func (dec *Decoder) AddFloat32(v *float32) error

AddFloat32 decodes the next key to a *float64. If next key value overflows float64, an InvalidUnmarshalError error will be returned.

func (*Decoder) AddInt

func (dec *Decoder) AddInt(v *int) error

AddInt decodes the next key to an *int. If next key value overflows int, an InvalidUnmarshalError error will be returned.

func (*Decoder) AddInt16

func (dec *Decoder) AddInt16(v *int16) error

AddInt16 decodes the next key to an *int. If next key value overflows int16, an InvalidUnmarshalError error will be returned.

func (*Decoder) AddInt32

func (dec *Decoder) AddInt32(v *int32) error

AddInt32 decodes the next key to an *int. If next key value overflows int32, an InvalidUnmarshalError error will be returned.

func (*Decoder) AddInt64

func (dec *Decoder) AddInt64(v *int64) error

AddInt64 decodes the next key to an *int. If next key value overflows int64, an InvalidUnmarshalError error will be returned.

func (*Decoder) AddInt8

func (dec *Decoder) AddInt8(v *int8) error

AddInt8 decodes the next key to an *int. If next key value overflows int8, an InvalidUnmarshalError error will be returned.

func (*Decoder) AddObject

func (dec *Decoder) AddObject(v UnmarshalerJSONObject) error

AddObject decodes the next key to a UnmarshalerJSONObject.

func (*Decoder) AddString

func (dec *Decoder) AddString(v *string) error

AddString decodes the next key to a *string. If next key is not a JSON string nor null, InvalidUnmarshalError will be returned.

func (*Decoder) AddUint16

func (dec *Decoder) AddUint16(v *uint16) error

AddUint16 decodes the next key to an *int. If next key value overflows uint16, an InvalidUnmarshalError error will be returned.

func (*Decoder) AddUint32

func (dec *Decoder) AddUint32(v *uint32) error

AddUint32 decodes the next key to an *int. If next key value overflows uint32, an InvalidUnmarshalError error will be returned.

func (*Decoder) AddUint64

func (dec *Decoder) AddUint64(v *uint64) error

AddUint64 decodes the next key to an *int. If next key value overflows uint64, an InvalidUnmarshalError error will be returned.

func (*Decoder) AddUint8

func (dec *Decoder) AddUint8(v *uint8) error

AddUint8 decodes the next key to an *int. If next key value overflows uint8, an InvalidUnmarshalError error will be returned.

func (*Decoder) Array

func (dec *Decoder) Array(value UnmarshalerJSONArray) error

Array decodes the next key to a UnmarshalerJSONArray.

func (*Decoder) Bool

func (dec *Decoder) Bool(v *bool) error

Bool decodes the next key to a *bool. If next key is neither null nor a JSON boolean, an InvalidUnmarshalError will be returned. If next key is null, bool will be false.

func (*Decoder) Decode

func (dec *Decoder) Decode(v interface{}) error

Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeArray

func (dec *Decoder) DecodeArray(arr UnmarshalerJSONArray) error

DecodeArray reads the next JSON-encoded value from its input and stores it in the value pointed to by v.

v must implement UnmarshalerJSONArray.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeBool

func (dec *Decoder) DecodeBool(v *bool) error

DecodeBool reads the next JSON-encoded value from its input and stores it in the boolean pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeFloat32

func (dec *Decoder) DecodeFloat32(v *float32) error

DecodeFloat32 reads the next JSON-encoded value from its input and stores it in the float32 pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeFloat64

func (dec *Decoder) DecodeFloat64(v *float64) error

DecodeFloat64 reads the next JSON-encoded value from its input and stores it in the float64 pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeInt

func (dec *Decoder) DecodeInt(v *int) error

DecodeInt reads the next JSON-encoded value from its input and stores it in the int pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeInt16

func (dec *Decoder) DecodeInt16(v *int16) error

DecodeInt16 reads the next JSON-encoded value from its input and stores it in the int16 pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeInt32

func (dec *Decoder) DecodeInt32(v *int32) error

DecodeInt32 reads the next JSON-encoded value from its input and stores it in the int32 pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeInt64

func (dec *Decoder) DecodeInt64(v *int64) error

DecodeInt64 reads the next JSON-encoded value from its input and stores it in the int64 pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeInt8

func (dec *Decoder) DecodeInt8(v *int8) error

DecodeInt8 reads the next JSON-encoded value from its input and stores it in the int8 pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeObject

func (dec *Decoder) DecodeObject(j UnmarshalerJSONObject) error

DecodeObject reads the next JSON-encoded value from its input and stores it in the value pointed to by v.

v must implement UnmarshalerJSONObject.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeString

func (dec *Decoder) DecodeString(v *string) error

DecodeString reads the next JSON-encoded value from its input and stores it in the string pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeUint16

func (dec *Decoder) DecodeUint16(v *uint16) error

DecodeUint16 reads the next JSON-encoded value from its input and stores it in the uint16 pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeUint32

func (dec *Decoder) DecodeUint32(v *uint32) error

DecodeUint32 reads the next JSON-encoded value from its input and stores it in the uint32 pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeUint64

func (dec *Decoder) DecodeUint64(v *uint64) error

DecodeUint64 reads the next JSON-encoded value from its input and stores it in the uint64 pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) DecodeUint8

func (dec *Decoder) DecodeUint8(v *uint8) error

DecodeUint8 reads the next JSON-encoded value from its input and stores it in the uint8 pointed to by v.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*Decoder) Float

func (dec *Decoder) Float(v *float64) error

Float decodes the next key to a *float64. If next key value overflows float64, an InvalidUnmarshalError error will be returned.

func (*Decoder) Float32

func (dec *Decoder) Float32(v *float32) error

Float32 decodes the next key to a *float64. If next key value overflows float64, an InvalidUnmarshalError error will be returned.

func (*Decoder) Int

func (dec *Decoder) Int(v *int) error

Int decodes the next key to an *int. If next key value overflows int, an InvalidUnmarshalError error will be returned.

func (*Decoder) Int16

func (dec *Decoder) Int16(v *int16) error

Int16 decodes the next key to an *int. If next key value overflows int16, an InvalidUnmarshalError error will be returned.

func (*Decoder) Int32

func (dec *Decoder) Int32(v *int32) error

Int32 decodes the next key to an *int. If next key value overflows int32, an InvalidUnmarshalError error will be returned.

func (*Decoder) Int64

func (dec *Decoder) Int64(v *int64) error

Int64 decodes the next key to an *int. If next key value overflows int64, an InvalidUnmarshalError error will be returned.

func (*Decoder) Int8

func (dec *Decoder) Int8(v *int8) error

Int8 decodes the next key to an *int. If next key value overflows int8, an InvalidUnmarshalError error will be returned.

func (*Decoder) Object

func (dec *Decoder) Object(value UnmarshalerJSONObject) error

Object decodes the next key to a UnmarshalerJSONObject.

func (*Decoder) Release

func (dec *Decoder) Release()

Release sends back a Decoder to the pool. If a decoder is used after calling Release a panic will be raised with an InvalidUsagePooledDecoderError error.

func (*Decoder) String

func (dec *Decoder) String(v *string) error

String decodes the next key to a *string. If next key is not a JSON string nor null, InvalidUnmarshalError will be returned.

func (*Decoder) Uint16

func (dec *Decoder) Uint16(v *uint16) error

Uint16 decodes the next key to an *int. If next key value overflows uint16, an InvalidUnmarshalError error will be returned.

func (*Decoder) Uint32

func (dec *Decoder) Uint32(v *uint32) error

Uint32 decodes the next key to an *int. If next key value overflows uint32, an InvalidUnmarshalError error will be returned.

func (*Decoder) Uint64

func (dec *Decoder) Uint64(v *uint64) error

Uint64 decodes the next key to an *int. If next key value overflows uint64, an InvalidUnmarshalError error will be returned.

func (*Decoder) Uint8

func (dec *Decoder) Uint8(v *uint8) error

Uint8 decodes the next key to an *int. If next key value overflows uint8, an InvalidUnmarshalError error will be returned.

type EmbeddedJSON

type EmbeddedJSON []byte

EmbeddedJSON is a raw encoded JSON value. It can be used to delay JSON decoding or precompute a JSON encoding.

type EncodeObjectFunc

type EncodeObjectFunc func(*Encoder)

EncodeObjectFunc is a custom func type implementing MarshaleObject. Use it to cast a func(*Encoder) to Marshal an object.

enc := gojay.NewEncoder(io.Writer)
enc.EncodeObject(gojay.EncodeObjectFunc(func(enc *gojay.Encoder) {
	enc.AddStringKey("hello", "world")
}))

func (EncodeObjectFunc) IsNil

func (f EncodeObjectFunc) IsNil() bool

IsNil implements MarshalerJSONObject.

func (EncodeObjectFunc) MarshalJSONObject

func (f EncodeObjectFunc) MarshalJSONObject(enc *Encoder)

MarshalJSONObject implements MarshalerJSONObject.

type Encoder

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

An Encoder writes JSON values to an output stream.

func BorrowEncoder

func BorrowEncoder(w io.Writer) *Encoder

BorrowEncoder borrows an Encoder from the pool.

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder or borrows one from the pool

func (*Encoder) AddArray

func (enc *Encoder) AddArray(v MarshalerJSONArray)

AddArray adds an implementation of MarshalerJSONArray to be encoded, must be used inside a slice or array encoding (does not encode a key) value must implement Marshaler

func (*Encoder) AddArrayKey

func (enc *Encoder) AddArrayKey(key string, v MarshalerJSONArray)

AddArrayKey adds an array or slice to be encoded, must be used inside an object as it will encode a key value must implement Marshaler

func (*Encoder) AddArrayKeyOmitEmpty

func (enc *Encoder) AddArrayKeyOmitEmpty(key string, v MarshalerJSONArray)

AddArrayKeyOmitEmpty adds an array or slice to be encoded and skips it if it is nil. Must be called inside an object as it will encode a key.

func (*Encoder) AddArrayOmitEmpty

func (enc *Encoder) AddArrayOmitEmpty(v MarshalerJSONArray)

AddArrayOmitEmpty adds an array or slice to be encoded, must be used inside a slice or array encoding (does not encode a key) value must implement Marshaler

func (*Encoder) AddBool

func (enc *Encoder) AddBool(v bool)

AddBool adds a bool to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) AddBoolKey

func (enc *Encoder) AddBoolKey(key string, v bool)

AddBoolKey adds a bool to be encoded, must be used inside an object as it will encode a key.

func (*Encoder) AddBoolKeyOmitEmpty

func (enc *Encoder) AddBoolKeyOmitEmpty(key string, v bool)

AddBoolKeyOmitEmpty adds a bool to be encoded and skips it if it is zero value. Must be used inside an object as it will encode a key.

func (*Encoder) AddBoolOmitEmpty

func (enc *Encoder) AddBoolOmitEmpty(v bool)

AddBoolOmitEmpty adds a bool to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) AddEmbeddedJSON

func (enc *Encoder) AddEmbeddedJSON(v *EmbeddedJSON)

AddEmbeddedJSON adds an EmbeddedJSON to be encoded.

It basically blindly writes the bytes to the final buffer. Therefore, it expects the JSON to be of proper format.

func (*Encoder) AddEmbeddedJSONKey

func (enc *Encoder) AddEmbeddedJSONKey(key string, v *EmbeddedJSON)

AddEmbeddedJSONKey adds an EmbeddedJSON and a key to be encoded.

It basically blindly writes the bytes to the final buffer. Therefore, it expects the JSON to be of proper format.

func (*Encoder) AddEmbeddedJSONKeyOmitEmpty

func (enc *Encoder) AddEmbeddedJSONKeyOmitEmpty(key string, v *EmbeddedJSON)

AddEmbeddedJSONKeyOmitEmpty adds an EmbeddedJSON and a key to be encoded or skips it if nil pointer or empty.

It basically blindly writes the bytes to the final buffer. Therefore, it expects the JSON to be of proper format.

func (*Encoder) AddEmbeddedJSONOmitEmpty

func (enc *Encoder) AddEmbeddedJSONOmitEmpty(v *EmbeddedJSON)

AddEmbeddedJSONOmitEmpty adds an EmbeddedJSON to be encoded or skips it if nil pointer or empty.

It basically blindly writes the bytes to the final buffer. Therefore, it expects the JSON to be of proper format.

func (*Encoder) AddFloat

func (enc *Encoder) AddFloat(v float64)

AddFloat adds a float64 to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) AddFloat32

func (enc *Encoder) AddFloat32(v float32)

AddFloat32 adds a float32 to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) AddFloat32Key

func (enc *Encoder) AddFloat32Key(key string, v float32)

AddFloat32Key adds a float32 to be encoded, must be used inside an object as it will encode a key

func (*Encoder) AddFloat32KeyOmitEmpty

func (enc *Encoder) AddFloat32KeyOmitEmpty(key string, v float32)

AddFloat32KeyOmitEmpty adds a float64 to be encoded and skips it if its value is 0. Must be used inside an object as it will encode a key

func (*Encoder) AddFloat32OmitEmpty

func (enc *Encoder) AddFloat32OmitEmpty(v float32)

AddFloat32OmitEmpty adds an int to be encoded and skips it if its value is 0, must be used inside a slice or array encoding (does not encode a key).

func (*Encoder) AddFloatKey

func (enc *Encoder) AddFloatKey(key string, v float64)

AddFloatKey adds a float64 to be encoded, must be used inside an object as it will encode a key

func (*Encoder) AddFloatKeyOmitEmpty

func (enc *Encoder) AddFloatKeyOmitEmpty(key string, v float64)

AddFloatKeyOmitEmpty adds a float64 to be encoded and skips it if its value is 0. Must be used inside an object as it will encode a key

func (*Encoder) AddFloatOmitEmpty

func (enc *Encoder) AddFloatOmitEmpty(v float64)

AddFloatOmitEmpty adds a float64 to be encoded and skips it if its value is 0, must be used inside a slice or array encoding (does not encode a key).

func (*Encoder) AddInt

func (enc *Encoder) AddInt(v int)

AddInt adds an int to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) AddInt64

func (enc *Encoder) AddInt64(v int64)

AddInt64 adds an int to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) AddInt64Key

func (enc *Encoder) AddInt64Key(key string, v int64)

AddInt64Key adds an int64 to be encoded, must be used inside an object as it will encode a key

func (*Encoder) AddInt64KeyOmitEmpty

func (enc *Encoder) AddInt64KeyOmitEmpty(key string, v int64)

AddInt64KeyOmitEmpty adds an int64 to be encoded and skips it if its value is 0. Must be used inside an object as it will encode a key.

func (*Encoder) AddInt64OmitEmpty

func (enc *Encoder) AddInt64OmitEmpty(v int64)

AddInt64OmitEmpty adds an int to be encoded and skips it if its value is 0, must be used inside a slice or array encoding (does not encode a key).

func (*Encoder) AddIntKey

func (enc *Encoder) AddIntKey(key string, v int)

AddIntKey adds an int to be encoded, must be used inside an object as it will encode a key

func (*Encoder) AddIntKeyOmitEmpty

func (enc *Encoder) AddIntKeyOmitEmpty(key string, v int)

AddIntKeyOmitEmpty adds an int to be encoded and skips it if its value is 0. Must be used inside an object as it will encode a key.

func (*Encoder) AddIntOmitEmpty

func (enc *Encoder) AddIntOmitEmpty(v int)

AddIntOmitEmpty adds an int to be encoded and skips it if its value is 0, must be used inside a slice or array encoding (does not encode a key).

func (*Encoder) AddInterface

func (enc *Encoder) AddInterface(value interface{})

AddInterface adds an interface{} to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) AddInterfaceKey

func (enc *Encoder) AddInterfaceKey(key string, value interface{})

AddInterfaceKey adds an interface{} to be encoded, must be used inside an object as it will encode a key

func (*Encoder) AddInterfaceKeyOmitEmpty

func (enc *Encoder) AddInterfaceKeyOmitEmpty(key string, v interface{})

AddInterfaceKeyOmitEmpty adds an interface{} to be encoded, must be used inside an object as it will encode a key

func (*Encoder) AddObject

func (enc *Encoder) AddObject(v MarshalerJSONObject)

AddObject adds an object to be encoded, must be used inside a slice or array encoding (does not encode a key) value must implement MarshalerJSONObject

func (*Encoder) AddObjectKey

func (enc *Encoder) AddObjectKey(key string, v MarshalerJSONObject)

AddObjectKey adds a struct to be encoded, must be used inside an object as it will encode a key value must implement MarshalerJSONObject

func (*Encoder) AddObjectKeyOmitEmpty

func (enc *Encoder) AddObjectKeyOmitEmpty(key string, v MarshalerJSONObject)

AddObjectKeyOmitEmpty adds an object to be encoded or skips it if IsNil returns true. Must be used inside a slice or array encoding (does not encode a key) value must implement MarshalerJSONObject

func (*Encoder) AddObjectOmitEmpty

func (enc *Encoder) AddObjectOmitEmpty(v MarshalerJSONObject)

AddObjectOmitEmpty adds an object to be encoded or skips it if IsNil returns true. Must be used inside a slice or array encoding (does not encode a key) value must implement MarshalerJSONObject

func (*Encoder) AddString

func (enc *Encoder) AddString(v string)

AddString adds a string to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) AddStringKey

func (enc *Encoder) AddStringKey(key, v string)

AddStringKey adds a string to be encoded, must be used inside an object as it will encode a key

func (*Encoder) AddStringKeyOmitEmpty

func (enc *Encoder) AddStringKeyOmitEmpty(key, v string)

AddStringKeyOmitEmpty adds a string to be encoded or skips it if it is zero value. Must be used inside an object as it will encode a key

func (*Encoder) AddStringOmitEmpty

func (enc *Encoder) AddStringOmitEmpty(v string)

AddStringOmitEmpty adds a string to be encoded or skips it if it is zero value. Must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) AddUint64

func (enc *Encoder) AddUint64(v uint64)

AddUint64 adds an int to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) AddUint64Key

func (enc *Encoder) AddUint64Key(key string, v uint64)

AddUint64Key adds an int to be encoded, must be used inside an object as it will encode a key

func (*Encoder) AddUint64KeyOmitEmpty

func (enc *Encoder) AddUint64KeyOmitEmpty(key string, v uint64)

AddUint64KeyOmitEmpty adds an int to be encoded and skips it if its value is 0. Must be used inside an object as it will encode a key.

func (*Encoder) AddUint64OmitEmpty

func (enc *Encoder) AddUint64OmitEmpty(v uint64)

AddUint64OmitEmpty adds an int to be encoded and skips it if its value is 0, must be used inside a slice or array encoding (does not encode a key).

func (*Encoder) AppendByte

func (enc *Encoder) AppendByte(b byte)

AppendByte allows a modular usage by appending a single byte manually to the current state of the buffer.

func (*Encoder) AppendBytes

func (enc *Encoder) AppendBytes(b []byte)

AppendBytes allows a modular usage by appending bytes manually to the current state of the buffer.

func (*Encoder) AppendString

func (enc *Encoder) AppendString(v string)

AppendString appends a string to the buffer

func (*Encoder) Array

func (enc *Encoder) Array(v MarshalerJSONArray)

Array adds an implementation of MarshalerJSONArray to be encoded, must be used inside a slice or array encoding (does not encode a key) value must implement Marshaler

func (*Encoder) ArrayKey

func (enc *Encoder) ArrayKey(key string, v MarshalerJSONArray)

ArrayKey adds an array or slice to be encoded, must be used inside an object as it will encode a key value must implement Marshaler

func (*Encoder) ArrayKeyOmitEmpty

func (enc *Encoder) ArrayKeyOmitEmpty(key string, v MarshalerJSONArray)

ArrayKeyOmitEmpty adds an array or slice to be encoded and skips it if it is nil. Must be called inside an object as it will encode a key.

func (*Encoder) ArrayOmitEmpty

func (enc *Encoder) ArrayOmitEmpty(v MarshalerJSONArray)

ArrayOmitEmpty adds an array or slice to be encoded, must be used inside a slice or array encoding (does not encode a key) value must implement Marshaler

func (*Encoder) Bool

func (enc *Encoder) Bool(v bool)

Bool adds a bool to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) BoolKey

func (enc *Encoder) BoolKey(key string, value bool)

BoolKey adds a bool to be encoded, must be used inside an object as it will encode a key.

func (*Encoder) BoolKeyOmitEmpty

func (enc *Encoder) BoolKeyOmitEmpty(key string, v bool)

BoolKeyOmitEmpty adds a bool to be encoded and skips it if it is zero value. Must be used inside an object as it will encode a key.

func (*Encoder) BoolOmitEmpty

func (enc *Encoder) BoolOmitEmpty(v bool)

BoolOmitEmpty adds a bool to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) Buf

func (enc *Encoder) Buf() []byte

Buf returns the Encoder's buffer.

func (*Encoder) Encode

func (enc *Encoder) Encode(v interface{}) error

Encode encodes a value to JSON.

If Encode cannot find a way to encode the type to JSON it will return an InvalidMarshalError.

func (*Encoder) EncodeArray

func (enc *Encoder) EncodeArray(v MarshalerJSONArray) error

EncodeArray encodes an implementation of MarshalerJSONArray to JSON

func (*Encoder) EncodeBool

func (enc *Encoder) EncodeBool(v bool) error

EncodeBool encodes a bool to JSON

func (*Encoder) EncodeEmbeddedJSON

func (enc *Encoder) EncodeEmbeddedJSON(v *EmbeddedJSON) error

EncodeEmbeddedJSON encodes an embedded JSON. is basically sets the internal buf as the value pointed by v and calls the io.Writer.Write()

func (*Encoder) EncodeFloat

func (enc *Encoder) EncodeFloat(n float64) error

EncodeFloat encodes a float64 to JSON

func (*Encoder) EncodeFloat32

func (enc *Encoder) EncodeFloat32(n float32) error

EncodeFloat32 encodes a float32 to JSON

func (*Encoder) EncodeInt

func (enc *Encoder) EncodeInt(n int) error

EncodeInt encodes an int to JSON

func (*Encoder) EncodeInt64

func (enc *Encoder) EncodeInt64(n int64) error

EncodeInt64 encodes an int64 to JSON

func (*Encoder) EncodeObject

func (enc *Encoder) EncodeObject(v MarshalerJSONObject) error

EncodeObject encodes an object to JSON

func (*Encoder) EncodeString

func (enc *Encoder) EncodeString(s string) error

EncodeString encodes a string to

func (*Encoder) EncodeUint64

func (enc *Encoder) EncodeUint64(n uint64) error

EncodeUint64 encodes an int64 to JSON

func (*Encoder) Float

func (enc *Encoder) Float(v float64)

Float adds a float64 to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) Float32

func (enc *Encoder) Float32(v float32)

Float32 adds a float32 to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) Float32Key

func (enc *Encoder) Float32Key(key string, v float32)

Float32Key adds a float32 to be encoded, must be used inside an object as it will encode a key

func (*Encoder) Float32KeyOmitEmpty

func (enc *Encoder) Float32KeyOmitEmpty(key string, v float32)

Float32KeyOmitEmpty adds a float64 to be encoded and skips it if its value is 0. Must be used inside an object as it will encode a key

func (*Encoder) Float32OmitEmpty

func (enc *Encoder) Float32OmitEmpty(v float32)

Float32OmitEmpty adds an int to be encoded and skips it if its value is 0, must be used inside a slice or array encoding (does not encode a key).

func (*Encoder) FloatKey

func (enc *Encoder) FloatKey(key string, value float64)

FloatKey adds a float64 to be encoded, must be used inside an object as it will encode a key

func (*Encoder) FloatKeyOmitEmpty

func (enc *Encoder) FloatKeyOmitEmpty(key string, v float64)

FloatKeyOmitEmpty adds a float64 to be encoded and skips it if its value is 0. Must be used inside an object as it will encode a key

func (*Encoder) FloatOmitEmpty

func (enc *Encoder) FloatOmitEmpty(v float64)

FloatOmitEmpty adds a float64 to be encoded and skips it if its value is 0, must be used inside a slice or array encoding (does not encode a key).

func (*Encoder) Int

func (enc *Encoder) Int(v int)

Int adds an int to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) Int64

func (enc *Encoder) Int64(v int64)

Int64 adds an int to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) Int64Key

func (enc *Encoder) Int64Key(key string, v int64)

Int64Key adds an int64 to be encoded, must be used inside an object as it will encode a key

func (*Encoder) Int64KeyOmitEmpty

func (enc *Encoder) Int64KeyOmitEmpty(key string, v int64)

Int64KeyOmitEmpty adds an int64 to be encoded and skips it if its value is 0. Must be used inside an object as it will encode a key.

func (*Encoder) Int64OmitEmpty

func (enc *Encoder) Int64OmitEmpty(v int64)

Int64OmitEmpty adds an int to be encoded and skips it if its value is 0, must be used inside a slice or array encoding (does not encode a key).

func (*Encoder) IntKey

func (enc *Encoder) IntKey(key string, v int)

IntKey adds an int to be encoded, must be used inside an object as it will encode a key

func (*Encoder) IntKeyOmitEmpty

func (enc *Encoder) IntKeyOmitEmpty(key string, v int)

IntKeyOmitEmpty adds an int to be encoded and skips it if its value is 0. Must be used inside an object as it will encode a key.

func (*Encoder) IntOmitEmpty

func (enc *Encoder) IntOmitEmpty(v int)

IntOmitEmpty adds an int to be encoded and skips it if its value is 0, must be used inside a slice or array encoding (does not encode a key).

func (*Encoder) Object

func (enc *Encoder) Object(v MarshalerJSONObject)

Object adds an object to be encoded, must be used inside a slice or array encoding (does not encode a key) value must implement MarshalerJSONObject

func (*Encoder) ObjectKey

func (enc *Encoder) ObjectKey(key string, value MarshalerJSONObject)

ObjectKey adds a struct to be encoded, must be used inside an object as it will encode a key value must implement MarshalerJSONObject

func (*Encoder) ObjectKeyOmitEmpty

func (enc *Encoder) ObjectKeyOmitEmpty(key string, value MarshalerJSONObject)

ObjectKeyOmitEmpty adds an object to be encoded or skips it if IsNil returns true. Must be used inside a slice or array encoding (does not encode a key) value must implement MarshalerJSONObject

func (*Encoder) ObjectOmitEmpty

func (enc *Encoder) ObjectOmitEmpty(v MarshalerJSONObject)

ObjectOmitEmpty adds an object to be encoded or skips it if IsNil returns true. Must be used inside a slice or array encoding (does not encode a key) value must implement MarshalerJSONObject

func (*Encoder) Release

func (enc *Encoder) Release()

Release sends back a Encoder to the pool.

func (*Encoder) String

func (enc *Encoder) String(v string)

String adds a string to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) StringKey

func (enc *Encoder) StringKey(key, v string)

StringKey adds a string to be encoded, must be used inside an object as it will encode a key

func (*Encoder) StringKeyOmitEmpty

func (enc *Encoder) StringKeyOmitEmpty(key, v string)

StringKeyOmitEmpty adds a string to be encoded or skips it if it is zero value. Must be used inside an object as it will encode a key

func (*Encoder) StringOmitEmpty

func (enc *Encoder) StringOmitEmpty(v string)

StringOmitEmpty adds a string to be encoded or skips it if it is zero value. Must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) Uint64

func (enc *Encoder) Uint64(v uint64)

Uint64 adds an int to be encoded, must be used inside a slice or array encoding (does not encode a key)

func (*Encoder) Uint64Key

func (enc *Encoder) Uint64Key(key string, v uint64)

Uint64Key adds an int to be encoded, must be used inside an object as it will encode a key

func (*Encoder) Uint64KeyOmitEmpty

func (enc *Encoder) Uint64KeyOmitEmpty(key string, v uint64)

Uint64KeyOmitEmpty adds an int to be encoded and skips it if its value is 0. Must be used inside an object as it will encode a key.

func (*Encoder) Uint64OmitEmpty

func (enc *Encoder) Uint64OmitEmpty(v uint64)

Uint64OmitEmpty adds an int to be encoded and skips it if its value is 0, must be used inside a slice or array encoding (does not encode a key).

func (*Encoder) Write

func (enc *Encoder) Write() (int, error)

Write writes to the io.Writer and resets the buffer.

type InvalidJSONError

type InvalidJSONError string

InvalidJSONError is a type representing an error returned when Decoding encounters invalid JSON.

func (InvalidJSONError) Error

func (err InvalidJSONError) Error() string

type InvalidMarshalError

type InvalidMarshalError string

InvalidMarshalError is a type representing an error returned when Encoding did not find the proper way to encode

func (InvalidMarshalError) Error

func (err InvalidMarshalError) Error() string

type InvalidUnmarshalError

type InvalidUnmarshalError string

InvalidUnmarshalError is a type representing an error returned when Decoding cannot unmarshal JSON to the receiver type for various reasons.

func (InvalidUnmarshalError) Error

func (err InvalidUnmarshalError) Error() string

type InvalidUsagePooledDecoderError

type InvalidUsagePooledDecoderError string

InvalidUsagePooledDecoderError is a type representing an error returned when decoding is called on a still pooled Decoder

func (InvalidUsagePooledDecoderError) Error

type InvalidUsagePooledEncoderError

type InvalidUsagePooledEncoderError string

InvalidUsagePooledEncoderError is a type representing an error returned when decoding is called on a still pooled Encoder

func (InvalidUsagePooledEncoderError) Error

type MarshalerJSONArray

type MarshalerJSONArray interface {
	MarshalJSONArray(enc *Encoder)
	IsNil() bool
}

MarshalerJSONArray is the interface to implement for a slice or an array to be encoded

type MarshalerJSONObject

type MarshalerJSONObject interface {
	MarshalJSONObject(enc *Encoder)
	IsNil() bool
}

MarshalerJSONObject is the interface to implement for struct to be encoded

type MarshalerStream

type MarshalerStream interface {
	MarshalStream(enc *StreamEncoder)
}

MarshalerStream is the interface to implement to continuously encode of stream of data.

type NoReaderError

type NoReaderError string

NoReaderError is a type representing an error returned when decoding requires a reader and none was given

func (NoReaderError) Error

func (err NoReaderError) Error() string

type StreamDecoder

type StreamDecoder struct {
	*Decoder
	// contains filtered or unexported fields
}

A StreamDecoder reads and decodes JSON values from an input stream.

It implements conext.Context and provide a channel to notify interruption.

func (*StreamDecoder) Deadline

func (dec *StreamDecoder) Deadline() (time.Time, bool)

Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results.

func (*StreamDecoder) DecodeStream

func (dec *StreamDecoder) DecodeStream(c UnmarshalerStream) error

DecodeStream reads the next line delimited JSON-encoded value from its input and stores it in the value pointed to by c.

c must implement UnmarshalerStream. Ideally c is a channel. See example for implementation.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

func (*StreamDecoder) Done

func (dec *StreamDecoder) Done() <-chan struct{}

Done returns a channel that's closed when work is done. It implements context.Context

func (*StreamDecoder) Err

func (dec *StreamDecoder) Err() error

Err returns nil if Done is not yet closed. If Done is closed, Err returns a non-nil error explaining why. It implements context.Context

func (*StreamDecoder) Release

func (dec *StreamDecoder) Release()

Release sends back a Decoder to the pool. If a decoder is used after calling Release a panic will be raised with an InvalidUsagePooledDecoderError error.

func (*StreamDecoder) SetDeadline

func (dec *StreamDecoder) SetDeadline(t time.Time)

SetDeadline sets the deadline

func (*StreamDecoder) Value

func (dec *StreamDecoder) Value(key interface{}) interface{}

Value implements context.Context

type StreamEncoder

type StreamEncoder struct {
	*Encoder
	// contains filtered or unexported fields
}

A StreamEncoder reads and encodes values to JSON from an input stream.

It implements conext.Context and provide a channel to notify interruption.

func (*StreamEncoder) AddArray

func (s *StreamEncoder) AddArray(v MarshalerJSONArray)

AddArray adds an implementation of MarshalerJSONArray to be encoded.

func (*StreamEncoder) AddFloat

func (s *StreamEncoder) AddFloat(value float64)

AddFloat adds a float64 to be encoded.

func (*StreamEncoder) AddInt

func (s *StreamEncoder) AddInt(value int)

AddInt adds an int to be encoded.

func (*StreamEncoder) AddObject

func (s *StreamEncoder) AddObject(v MarshalerJSONObject)

AddObject adds an object to be encoded. value must implement MarshalerJSONObject.

func (*StreamEncoder) AddString

func (s *StreamEncoder) AddString(v string)

AddString adds a string to be encoded.

func (*StreamEncoder) Cancel

func (s *StreamEncoder) Cancel(err error)

Cancel cancels the consumers of the stream, interrupting the stream encoding.

After calling cancel, Done() will return a closed channel.

func (*StreamEncoder) CommaDelimited

func (s *StreamEncoder) CommaDelimited() *StreamEncoder

CommaDelimited sets the delimiter to a comma.

It will add a new line after each JSON marshaled by the MarshalerStream

func (*StreamEncoder) Deadline

func (s *StreamEncoder) Deadline() (time.Time, bool)

Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results.

func (*StreamEncoder) Done

func (s *StreamEncoder) Done() <-chan struct{}

Done returns a channel that's closed when work is done. It implements context.Context

func (*StreamEncoder) EncodeStream

func (s *StreamEncoder) EncodeStream(m MarshalerStream)

EncodeStream spins up a defined number of non blocking consumers of the MarshalerStream m.

m must implement MarshalerStream. Ideally m is a channel. See example for implementation.

See the documentation for Marshal for details about the conversion of Go value to JSON.

func (*StreamEncoder) Err

func (s *StreamEncoder) Err() error

Err returns nil if Done is not yet closed. If Done is closed, Err returns a non-nil error explaining why. It implements context.Context

func (*StreamEncoder) LineDelimited

func (s *StreamEncoder) LineDelimited() *StreamEncoder

LineDelimited sets the delimiter to a new line character.

It will add a new line after each JSON marshaled by the MarshalerStream

func (*StreamEncoder) NConsumer

func (s *StreamEncoder) NConsumer(n int) *StreamEncoder

NConsumer sets the number of non blocking go routine to consume the stream.

func (*StreamEncoder) Release

func (s *StreamEncoder) Release()

Release sends back a Decoder to the pool. If a decoder is used after calling Release a panic will be raised with an InvalidUsagePooledDecoderError error.

func (*StreamEncoder) SetDeadline

func (s *StreamEncoder) SetDeadline(t time.Time)

SetDeadline sets the deadline

func (*StreamEncoder) Value

func (s *StreamEncoder) Value(key interface{}) interface{}

Value implements context.Context

type UnmarshalerJSONArray

type UnmarshalerJSONArray interface {
	UnmarshalJSONArray(*Decoder) error
}

UnmarshalerJSONArray is the interface to implement for a slice or an array to be decoded

type UnmarshalerJSONObject

type UnmarshalerJSONObject interface {
	UnmarshalJSONObject(*Decoder, string) error
	NKeys() int
}

UnmarshalerJSONObject is the interface to implement for a struct to be decoded

type UnmarshalerStream

type UnmarshalerStream interface {
	UnmarshalStream(*StreamDecoder) error
}

UnmarshalerStream is the interface to implement for a slice, an array or a slice to decode a line delimited JSON to.

Directories

Path Synopsis
examples
websocket
package main simulates a conversation between a given set of websocket clients and a server.
package main simulates a conversation between a given set of websocket clients and a server.

Jump to

Keyboard shortcuts

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