package jsoniter

Import Path
	github.com/json-iterator/go (on go.dev)

Dependency Relation
	imports 20 packages, and imported by one package

Involved Source Files adapter.go any.go any_array.go any_bool.go any_float.go any_int32.go any_int64.go any_invalid.go any_nil.go any_number.go any_object.go any_str.go any_uint32.go any_uint64.go config.go iter.go iter_array.go iter_float.go iter_int.go iter_object.go iter_skip.go iter_skip_strict.go iter_str.go Package jsoniter implements encoding and decoding of JSON as defined in RFC 4627 and provides interfaces with identical syntax of standard lib encoding/json. Converting from encoding/json to jsoniter is no more than replacing the package with jsoniter and variable type declarations (if any). jsoniter interfaces gives 100% compatibility with code using standard lib. "JSON and Go" (https://golang.org/doc/articles/json_and_go.html) gives a description of how Marshal/Unmarshal operate between arbitrary or predefined json objects and bytes, and it applies to jsoniter.Marshal/Unmarshal as well. Besides, jsoniter.Iterator provides a different set of interfaces iterating given bytes/string/reader and yielding parsed elements one by one. This set of interfaces reads input as required and gives better performance. pool.go reflect.go reflect_array.go reflect_dynamic.go reflect_extension.go reflect_json_number.go reflect_json_raw_message.go reflect_map.go reflect_marshaler.go reflect_native.go reflect_optional.go reflect_slice.go reflect_struct_decoder.go reflect_struct_encoder.go stream.go stream_float.go stream_int.go stream_str.go
Code Examples { type ColorGroup struct { ID int Name string Colors []string } group := ColorGroup{ ID: 1, Name: "Reds", Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, } stream := ConfigFastest.BorrowStream(nil) defer ConfigFastest.ReturnStream(stream) stream.WriteVal(group) if stream.Error != nil { fmt.Println("error:", stream.Error) } os.Stdout.Write(stream.Buffer()) } { var jsonBlob = []byte(`[ {"Name": "Platypus", "Order": "Monotremata"}, {"Name": "Quoll", "Order": "Dasyuromorphia"} ]`) type Animal struct { Name string Order string } var animals []Animal iter := ConfigFastest.BorrowIterator(jsonBlob) defer ConfigFastest.ReturnIterator(iter) iter.ReadVal(&animals) if iter.Error != nil { fmt.Println("error:", iter.Error) } fmt.Printf("%+v", animals) } { val := []byte(`{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}`) fmt.Printf(Get(val, "Colors", 0).ToString()) } { type ColorGroup struct { ID int Name string Colors []string } group := ColorGroup{ ID: 1, Name: "Reds", Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, } b, err := Marshal(group) if err != nil { fmt.Println("error:", err) } os.Stdout.Write(b) } { hello := MyKey("hello") output, _ := Marshal(map[*MyKey]string{&hello: "world"}) fmt.Println(string(output)) obj := map[*MyKey]string{} Unmarshal(output, &obj) for k, v := range obj { fmt.Println(*k, v) } } { var jsonBlob = []byte(`[ {"Name": "Platypus", "Order": "Monotremata"}, {"Name": "Quoll", "Order": "Dasyuromorphia"} ]`) type Animal struct { Name string Order string } var animals []Animal err := Unmarshal(jsonBlob, &animals) if err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", animals) }
Package-Level Type Names (total 122, in which 25 are exported)
/* sort exporteds by: | */
Any generic object representation. The lazy json implementation holds []byte and parse lazily. ( T) Get(path ...interface{}) Any ( T) GetInterface() interface{} ( T) Keys() []string ( T) LastError() error ( T) MustBeValid() Any ( T) Size() int ( T) ToBool() bool ( T) ToFloat32() float32 ( T) ToFloat64() float64 ( T) ToInt() int ( T) ToInt32() int32 ( T) ToInt64() int64 ( T) ToString() string ( T) ToUint() uint ( T) ToUint32() uint32 ( T) ToUint64() uint64 ( T) ToVal(val interface{}) ( T) ValueType() ValueType ( T) WriteTo(stream *Stream) func Get(data []byte, path ...interface{}) Any func Wrap(val interface{}) Any func WrapFloat64(val float64) Any func WrapInt32(val int32) Any func WrapInt64(val int64) Any func WrapString(val string) Any func WrapUint32(val uint32) Any func WrapUint64(val uint64) Any func Any.Get(path ...interface{}) Any func Any.MustBeValid() Any func API.Get(data []byte, path ...interface{}) Any func (*Iterator).ReadAny() Any
API the public interface of this package. Primary Marshal and Unmarshal. ( T) BorrowIterator(data []byte) *Iterator ( T) BorrowStream(writer io.Writer) *Stream ( T) DecoderOf(typ reflect2.Type) ValDecoder ( T) EncoderOf(typ reflect2.Type) ValEncoder ( T) Get(data []byte, path ...interface{}) Any ( T) Marshal(v interface{}) ([]byte, error) ( T) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) ( T) MarshalToString(v interface{}) (string, error) ( T) NewDecoder(reader io.Reader) *Decoder ( T) NewEncoder(writer io.Writer) *Encoder ( T) RegisterExtension(extension Extension) ( T) ReturnIterator(iter *Iterator) ( T) ReturnStream(stream *Stream) ( T) Unmarshal(data []byte, v interface{}) error ( T) UnmarshalFromString(str string, v interface{}) error ( T) Valid(data []byte) bool T : IteratorPool T : StreamPool func Config.Froze() API func NewIterator(cfg API) *Iterator func NewStream(cfg API, out io.Writer, bufSize int) *Stream func Parse(cfg API, reader io.Reader, bufSize int) *Iterator func ParseBytes(cfg API, input []byte) *Iterator func ParseString(cfg API, input string) *Iterator var ConfigCompatibleWithStandardLibrary var ConfigDefault var ConfigFastest
Binding describe how should we encode/decode the struct field Decoder ValDecoder Encoder ValEncoder Field reflect2.StructField FromNames []string ToNames []string func (*StructDescriptor).GetField(fieldName string) *Binding
Config customize how the API should behave. The API is created from Config by Froze. CaseSensitive bool DisallowUnknownFields bool EscapeHTML bool IndentionStep int MarshalFloatWith6Digits bool ObjectFieldMustBeSimpleString bool OnlyTaggedField bool SortMapKeys bool TagKey string UseNumber bool ValidateJsonRawMessage bool Froze forge API from config
Decoder reads and decodes JSON values from an input stream. Decoder provides identical APIs with json/stream Decoder (Token() and UseNumber() are in progress) Buffered remaining buffer Decode decode JSON into interface{} DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination. More is there more? UseNumber causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64. func NewDecoder(reader io.Reader) *Decoder func API.NewDecoder(reader io.Reader) *Decoder
CreateDecoder get decoder from map CreateEncoder No-op CreateMapKeyDecoder No-op CreateMapKeyEncoder No-op DecorateDecoder No-op DecorateEncoder No-op UpdateStructDescriptor No-op T : Extension
DecoderFunc the function form of TypeDecoder func RegisterFieldDecoderFunc(typ string, field string, fun DecoderFunc) func RegisterTypeDecoderFunc(typ string, fun DecoderFunc)
DummyExtension embed this type get dummy implementation for all methods of Extension CreateDecoder No-op CreateEncoder No-op CreateMapKeyDecoder No-op CreateMapKeyEncoder No-op DecorateDecoder No-op DecorateEncoder No-op UpdateStructDescriptor No-op *T : Extension
Encoder same as json.Encoder Encode encode interface{} as JSON to io.Writer SetEscapeHTML escape html by default, set to false to disable SetIndent set the indention. Prefix is not supported func NewEncoder(writer io.Writer) *Encoder func API.NewEncoder(writer io.Writer) *Encoder
CreateDecoder No-op CreateEncoder get encoder from map CreateMapKeyDecoder No-op CreateMapKeyEncoder No-op DecorateDecoder No-op DecorateEncoder No-op UpdateStructDescriptor No-op T : Extension
EncoderFunc the function form of TypeEncoder func RegisterFieldEncoderFunc(typ string, field string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) func RegisterTypeEncoderFunc(typ string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool)
Extension the one for all SPI. Customize encoding/decoding by specifying alternate encoder/decoder. Can also rename fields by UpdateStructDescriptor. ( T) CreateDecoder(typ reflect2.Type) ValDecoder ( T) CreateEncoder(typ reflect2.Type) ValEncoder ( T) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder ( T) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder ( T) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder ( T) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder ( T) UpdateStructDescriptor(structDescriptor *StructDescriptor) DecoderExtension *DummyExtension EncoderExtension func RegisterExtension(extension Extension) func API.RegisterExtension(extension Extension)
( T) IsEmbeddedPtrNil(ptr unsafe.Pointer) bool
Iterator is a io.Reader like object, with JSON specific read functions. Error is not returned as return value, but stored as Error member on this iterator instance. // open for customized decoder Error error CurrentBuffer gets current buffer as string for debugging purpose Pool returns a pool can provide more iterator with same configuration Read read the next JSON element as generic interface{}. ReadAny read next JSON element as an Any object. It is a better json.RawMessage. ReadArray read array element, tells if the array has more element to read. ReadArrayCB read array with callback ReadBigFloat read big.Float ReadBigInt read big.Int ReadBool reads a json object as BoolValue ReadFloat32 read float32 ReadFloat64 read float64 ReadInt read int ReadInt16 read int16 ReadInt32 read int32 ReadInt64 read int64 ReadInt8 read int8 ReadMapCB read map with callback, the key can be any string ReadNil reads a json object as nil and returns whether it's a nil or not ReadNumber read json.Number ReadObject read one field from object. If object ended, returns empty string. Otherwise, returns the field name. ReadObjectCB read object with callback, the key is ascii only and field name not copied ReadString read string from iterator ReadStringAsSlice read string from iterator without copying into string form. The []byte can not be kept, as it will change after next iterator call. ReadUint read uint ReadUint16 read uint16 ReadUint32 read uint32 ReadUint64 read uint64 ReadUint8 read uint8 ReadVal copy the underlying JSON into go interface, same as json.Unmarshal ReportError record a error in iterator instance with current position. Reset reuse iterator instance by specifying another reader ResetBytes reuse iterator instance by specifying another byte array as input Skip skips a json object and positions to relatively the next json object SkipAndAppendBytes skips next JSON element and appends its content to buffer, returning the result. SkipAndReturnBytes skip next JSON element, and return its content as []byte. The []byte can be kept, it is a copy of data. WhatIsNext gets ValueType of relatively next json element func NewIterator(cfg API) *Iterator func Parse(cfg API, reader io.Reader, bufSize int) *Iterator func ParseBytes(cfg API, input []byte) *Iterator func ParseString(cfg API, input string) *Iterator func API.BorrowIterator(data []byte) *Iterator func (*Iterator).Reset(reader io.Reader) *Iterator func (*Iterator).ResetBytes(input []byte) *Iterator func IteratorPool.BorrowIterator(data []byte) *Iterator func API.ReturnIterator(iter *Iterator) func IteratorPool.ReturnIterator(iter *Iterator) func (*OptionalDecoder).Decode(ptr unsafe.Pointer, iter *Iterator) func ValDecoder.Decode(ptr unsafe.Pointer, iter *Iterator)
IteratorPool a thread safe pool of iterators with same configuration ( T) BorrowIterator(data []byte) *Iterator ( T) ReturnIterator(iter *Iterator) API (interface) func (*Iterator).Pool() IteratorPool
Float64 returns the number as a float64. Int64 returns the number as an int64. String returns the literal text of the number. T : fmt.Stringer
ValueDecoder ValDecoder ValueType reflect2.Type (*T) Decode(ptr unsafe.Pointer, iter *Iterator) *T : ValDecoder
ValueEncoder ValEncoder (*T) Encode(ptr unsafe.Pointer, stream *Stream) (*T) IsEmpty(ptr unsafe.Pointer) bool *T : ValEncoder
RawMessage to make replace json with jsoniter
stream is a io.Writer like object, with JSON specific write functions. Error is not returned as return value, but stored as Error member on this stream instance. // open for customized encoder Error error Available returns how many bytes are unused in the buffer. Buffer if writer is nil, use this method to take the result Buffered returns the number of bytes that have been written into the current buffer. Flush writes any buffered data to the underlying io.Writer. Pool returns a pool can provide more stream with same configuration Reset reuse this stream instance by assign a new writer SetBuffer allows to append to the internal buffer directly Write writes the contents of p into the buffer. It returns the number of bytes written. If nn < len(p), it also returns an error explaining why the write is short. WriteArrayEnd write ] with possible indention WriteArrayStart write [ with possible indention WriteBool write true or false into stream WriteEmptyArray write [] WriteEmptyObject write {} WriteFalse write false to stream WriteFloat32 write float32 to stream WriteFloat32Lossy write float32 to stream with ONLY 6 digits precision although much much faster WriteFloat64 write float64 to stream WriteFloat64Lossy write float64 to stream with ONLY 6 digits precision although much much faster WriteInt write int to stream WriteInt16 write int16 to stream WriteInt32 write int32 to stream WriteInt64 write int64 to stream WriteInt8 write int8 to stream WriteMore write , with possible indention WriteNil write null to stream WriteObjectEnd write } with possible indention WriteObjectField write "field": with possible indention WriteObjectStart write { with possible indention WriteRaw write string out without quotes, just like []byte WriteString write string to stream without html escape WriteStringWithHTMLEscaped write string to stream with html special characters escaped WriteTrue write true to stream WriteUint write uint to stream WriteUint16 write uint16 to stream WriteUint32 write uint32 to stream WriteUint64 write uint64 to stream WriteUint8 write uint8 to stream WriteVal copy the go interface into underlying JSON, same as json.Marshal *T : io.Writer func NewStream(cfg API, out io.Writer, bufSize int) *Stream func API.BorrowStream(writer io.Writer) *Stream func StreamPool.BorrowStream(writer io.Writer) *Stream func Any.WriteTo(stream *Stream) func API.ReturnStream(stream *Stream) func (*OptionalEncoder).Encode(ptr unsafe.Pointer, stream *Stream) func StreamPool.ReturnStream(stream *Stream) func ValEncoder.Encode(ptr unsafe.Pointer, stream *Stream)
StreamPool a thread safe pool of streams with same configuration ( T) BorrowStream(writer io.Writer) *Stream ( T) ReturnStream(stream *Stream) API (interface) func (*Stream).Pool() StreamPool
StructDescriptor describe how should we encode/decode the struct Fields []*Binding Type reflect2.Type GetField get one field from the descriptor by its name. Can not use map here to keep field orders. func DecoderExtension.UpdateStructDescriptor(structDescriptor *StructDescriptor) func (*DummyExtension).UpdateStructDescriptor(structDescriptor *StructDescriptor) func EncoderExtension.UpdateStructDescriptor(structDescriptor *StructDescriptor) func Extension.UpdateStructDescriptor(structDescriptor *StructDescriptor)
ValDecoder is an internal type registered to cache as needed. Don't confuse jsoniter.ValDecoder with json.Decoder. For json.Decoder's adapter, refer to jsoniter.AdapterDecoder(todo link). Reflection on type to create decoders, which is then cached Reflection on value is avoided as we can, as the reflect.Value itself will allocate, with following exceptions 1. create instance of new value, for example *int will need a int to be allocated 2. append to slice, if the existing cap is not enough, allocate will be done using Reflect.New 3. assignment to map, both key and value will be reflect.Value For a simple struct binding, it will be reflect.Value free and allocation free ( T) Decode(ptr unsafe.Pointer, iter *Iterator) *OptionalDecoder func API.DecoderOf(typ reflect2.Type) ValDecoder func DecoderExtension.CreateDecoder(typ reflect2.Type) ValDecoder func DecoderExtension.CreateMapKeyDecoder(typ reflect2.Type) ValDecoder func DecoderExtension.DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder func (*DummyExtension).CreateDecoder(typ reflect2.Type) ValDecoder func (*DummyExtension).CreateMapKeyDecoder(typ reflect2.Type) ValDecoder func (*DummyExtension).DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder func EncoderExtension.CreateDecoder(typ reflect2.Type) ValDecoder func EncoderExtension.CreateMapKeyDecoder(typ reflect2.Type) ValDecoder func EncoderExtension.DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder func Extension.CreateDecoder(typ reflect2.Type) ValDecoder func Extension.CreateMapKeyDecoder(typ reflect2.Type) ValDecoder func Extension.DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder func RegisterFieldDecoder(typ string, field string, decoder ValDecoder) func RegisterTypeDecoder(typ string, decoder ValDecoder) func DecoderExtension.DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder func (*DummyExtension).DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder func EncoderExtension.DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder func Extension.DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder
ValEncoder is an internal type registered to cache as needed. Don't confuse jsoniter.ValEncoder with json.Encoder. For json.Encoder's adapter, refer to jsoniter.AdapterEncoder(todo godoc link). ( T) Encode(ptr unsafe.Pointer, stream *Stream) ( T) IsEmpty(ptr unsafe.Pointer) bool *OptionalEncoder func API.EncoderOf(typ reflect2.Type) ValEncoder func DecoderExtension.CreateEncoder(typ reflect2.Type) ValEncoder func DecoderExtension.CreateMapKeyEncoder(typ reflect2.Type) ValEncoder func DecoderExtension.DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder func (*DummyExtension).CreateEncoder(typ reflect2.Type) ValEncoder func (*DummyExtension).CreateMapKeyEncoder(typ reflect2.Type) ValEncoder func (*DummyExtension).DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder func EncoderExtension.CreateEncoder(typ reflect2.Type) ValEncoder func EncoderExtension.CreateMapKeyEncoder(typ reflect2.Type) ValEncoder func EncoderExtension.DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder func Extension.CreateEncoder(typ reflect2.Type) ValEncoder func Extension.CreateMapKeyEncoder(typ reflect2.Type) ValEncoder func Extension.DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) func RegisterTypeEncoder(typ string, encoder ValEncoder) func DecoderExtension.DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder func (*DummyExtension).DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder func EncoderExtension.DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder func Extension.DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder
ValueType the type for JSON element func Any.ValueType() ValueType func (*Iterator).WhatIsNext() ValueType const ArrayValue const BoolValue const InvalidValue const NilValue const NumberValue const ObjectValue const StringValue
Package-Level Functions (total 91, in which 31 are exported)
func CastJsonNumber(val interface{}) (string, bool)
Get quick method to get value from deeply nested JSON structure
Marshal adapts to json/encoding Marshal API Marshal returns the JSON encoding of v, adapts to json/encoding Marshal API Refer to https://godoc.org/encoding/json#Marshal for more information
MarshalIndent same as json.MarshalIndent. Prefix is not supported.
MarshalToString convenient method to write as string instead of []byte
NewDecoder adapts to json/stream NewDecoder API. NewDecoder returns a new decoder that reads from r. Instead of a json/encoding Decoder, an Decoder is returned Refer to https://godoc.org/encoding/json#NewDecoder for more information
NewEncoder same as json.NewEncoder
NewIterator creates an empty Iterator instance
NewStream create new stream instance. cfg can be jsoniter.ConfigDefault. out can be nil if write to internal buffer. bufSize is the initial size for the internal buffer in bytes.
Parse creates an Iterator instance from io.Reader
ParseBytes creates an Iterator instance from byte array
ParseString creates an Iterator instance from string
RegisterExtension register extension
RegisterFieldDecoder register TypeDecoder for a struct field
RegisterFieldDecoderFunc register TypeDecoder for a struct field with function
RegisterFieldEncoder register TypeEncoder for a struct field
RegisterFieldEncoderFunc register TypeEncoder for a struct field with encode/isEmpty function
RegisterTypeDecoder register TypeDecoder for a typ
RegisterTypeDecoderFunc register TypeDecoder for a type with function
RegisterTypeEncoder register TypeEncoder for a type
RegisterTypeEncoderFunc register TypeEncoder for a type with encode/isEmpty function
Unmarshal adapts to json/encoding Unmarshal API Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. Refer to https://godoc.org/encoding/json#Unmarshal for more information
UnmarshalFromString is a convenient method to read from string instead of []byte
Valid reports whether data is a valid JSON encoding.
Wrap turn a go object into Any interface
WrapFloat64 turn float64 into Any interface
WrapInt32 turn int32 into Any interface
WrapInt64 turn int64 into Any interface
WrapString turn string into Any interface
WrapUint32 turn uint32 into Any interface
WrapUint64 turn uint64 into Any interface
Package-Level Variables (total 27, in which 3 are exported)
ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior
ConfigDefault the default API
ConfigFastest marshals float with only 6 digits precision
Package-Level Constants (total 32, in which 7 are exported)
ArrayValue JSON element []
BoolValue JSON element true or false
InvalidValue invalid JSON element
NilValue JSON element null
NumberValue JSON element 100 or 0.10
ObjectValue JSON element {}
StringValue JSON element "string"