jsoniter

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

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

Go to latest
Published: Jun 14, 2017 License: MIT Imports: 15 Imported by: 0

README

rcard

jsoniter (json-iterator) is fast and flexible JSON parser available in Java and Go

Benchmark

benchmark

Source code: https://github.com/json-iterator/go-benchmark/blob/master/src/github.com/json-iterator/go-benchmark/benchmark_medium_payload_test.go

Raw Result (easyjson requires static code generation)

ns/op allocation bytes allocation times
std decode 35510 ns/op 1960 B/op 99 allocs/op
easyjson decode 8499 ns/op 160 B/op 4 allocs/op
jsoniter decode 5623 ns/op 160 B/op 3 allocs/op
std encode 2213 ns/op 712 B/op 5 allocs/op
easyjson encode 883 ns/op 576 B/op 3 allocs/op
jsoniter encode 837 ns/op 384 B/op 4 allocs/op

Usage

100% compatibility with standard lib

Replace

import "encoding/json"
json.Marshal(&data)

with

import "github.com/json-iterator/go"
jsoniter.Marshal(&data)

Replace

import "encoding/json"
json.Unmarshal(input, &data)

with

import "github.com/json-iterator/go"
jsoniter.Unmarshal(input, &data)

How to get

go get github.com/json-iterator/go

Contribution Welcomed !

Report issue or pull request, or email taowen@gmail.com, or Gitter chat

Documentation

Overview

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.

Index

Examples

Constants

This section is empty.

Variables

View Source
var DEFAULT_CONFIG = Config{}.Froze()

Functions

func Marshal

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

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

Example
type ColorGroup struct {
	ID     int
	Name   string
	Colors []string
}
group := ColorGroup{
	ID:     1,
	Name:   "Reds",
	Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := jsoniter.Marshal(group)
if err != nil {
	fmt.Println("error:", err)
}
os.Stdout.Write(b)
Output:

{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}

func MarshalToString

func MarshalToString(v interface{}) (string, error)

func RegisterExtension

func RegisterExtension(extension ExtensionFunc)

RegisterExtension can register a custom extension

func RegisterFieldDecoder

func RegisterFieldDecoder(typ string, field string, fun DecoderFunc)

RegisterFieldDecoder can register a type for json field

func RegisterFieldEncoder

func RegisterFieldEncoder(typ string, field string, fun EncoderFunc)

func RegisterTypeDecoder

func RegisterTypeDecoder(typ string, fun DecoderFunc)

RegisterTypeDecoder can register a type for json object

func RegisterTypeEncoder

func RegisterTypeEncoder(typ string, fun EncoderFunc)

func Unmarshal

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

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

Example
var jsonBlob = []byte(`[
		{"Name": "Platypus", "Order": "Monotremata"},
		{"Name": "Quoll",    "Order": "Dasyuromorphia"}
	]`)
type Animal struct {
	Name  string
	Order string
}
var animals []Animal
err := jsoniter.Unmarshal(jsonBlob, &animals)
if err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%+v", animals)
Output:

[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]

func UnmarshalFromString

func UnmarshalFromString(str string, v interface{}) error

Types

type AdaptedDecoder

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

AdaptedDecoder reads and decodes JSON values from an input stream. AdaptedDecoder provides identical APIs with json/stream Decoder (Token() and UseNumber() are in progress)

func NewDecoder

func NewDecoder(reader io.Reader) *AdaptedDecoder

NewDecoder adapts to json/stream NewDecoder API.

NewDecoder returns a new decoder that reads from r.

Instead of a json/encoding Decoder, an AdaptedDecoder is returned Refer to https://godoc.org/encoding/json#NewDecoder for more information

func (*AdaptedDecoder) Buffered

func (adapter *AdaptedDecoder) Buffered() io.Reader

func (*AdaptedDecoder) Decode

func (adapter *AdaptedDecoder) Decode(obj interface{}) error

func (*AdaptedDecoder) More

func (adapter *AdaptedDecoder) More() bool

func (*AdaptedDecoder) UseNumber

func (decoder *AdaptedDecoder) UseNumber()

type AdaptedEncoder

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

func NewEncoder

func NewEncoder(writer io.Writer) *AdaptedEncoder

func (*AdaptedEncoder) Encode

func (adapter *AdaptedEncoder) Encode(val interface{}) error

func (*AdaptedEncoder) SetIndent

func (adapter *AdaptedEncoder) SetIndent(prefix, indent string)

type Any

type Any interface {
	LastError() error
	ValueType() ValueType
	ToBool() bool
	ToInt() int
	ToInt32() int32
	ToInt64() int64
	ToUint() uint
	ToUint32() uint32
	ToUint64() uint64
	ToFloat32() float32
	ToFloat64() float64
	ToString() string
	Get(path ...interface{}) Any
	Size() int
	Keys() []string
	IterateObject() (func() (string, Any, bool), bool)
	IterateArray() (func() (Any, bool), bool)
	GetArray() []Any
	SetArray(newList []Any) bool
	GetObject() map[string]Any
	SetObject(map[string]Any) bool
	GetInterface() interface{}
	WriteTo(stream *Stream)
	Parse() *Iterator
}

func UnmarshalAny

func UnmarshalAny(data []byte) (Any, error)

UnmarshalAny adapts to

func UnmarshalAnyFromString

func UnmarshalAnyFromString(str string) (Any, error)

func Wrap

func Wrap(val interface{}) Any

func WrapFloat64

func WrapFloat64(val float64) Any

func WrapInt32

func WrapInt32(val int32) Any

func WrapInt64

func WrapInt64(val int64) Any

func WrapString

func WrapString(val string) Any

func WrapUint32

func WrapUint32(val uint32) Any

func WrapUint64

func WrapUint64(val uint64) Any

type Config

type Config struct {
	IndentionStep                 int
	MarshalFloatWith6Digits       bool
	SupportUnexportedStructFields bool
	Tag                           string
}

func (Config) Froze

func (cfg Config) Froze() *frozenConfig

type Decoder

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

Decoder is an internal type registered to cache as needed. Don't confuse jsoniter.Decoder 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

type DecoderFunc

type DecoderFunc func(ptr unsafe.Pointer, iter *Iterator)

type Encoder

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

Encoder is an internal type registered to cache as needed. Don't confuse jsoniter.Encoder with json.Encoder. For json.Encoder's adapter, refer to jsoniter.AdapterEncoder(todo godoc link).

type EncoderFunc

type EncoderFunc func(ptr unsafe.Pointer, stream *Stream)

type ExtensionFunc

type ExtensionFunc func(typ reflect.Type, field *reflect.StructField) ([]string, EncoderFunc, DecoderFunc)

type Iterator

type Iterator struct {
	Error error
	// contains filtered or unexported fields
}

Iterator is a fast and flexible JSON parser

func NewIterator

func NewIterator(cfg *frozenConfig) *Iterator

Create creates an empty Iterator instance

func Parse

func Parse(cfg *frozenConfig, reader io.Reader, bufSize int) *Iterator

Parse parses a json buffer in io.Reader into an Iterator instance

func ParseBytes

func ParseBytes(cfg *frozenConfig, input []byte) *Iterator

ParseBytes parses a json byte slice into an Iterator instance

func ParseString

func ParseString(cfg *frozenConfig, input string) *Iterator

ParseString parses a json string into an Iterator instance

func (*Iterator) CurrentBuffer

func (iter *Iterator) CurrentBuffer() string

CurrentBuffer gets current buffer as string

func (*Iterator) Read

func (iter *Iterator) Read() interface{}

func (*Iterator) ReadAny

func (iter *Iterator) ReadAny() Any

func (*Iterator) ReadArray

func (iter *Iterator) ReadArray() (ret bool)

func (*Iterator) ReadArrayCB

func (iter *Iterator) ReadArrayCB(callback func(*Iterator) bool) (ret bool)

func (*Iterator) ReadBase64

func (iter *Iterator) ReadBase64() (ret []byte)

ReadBase64 reads a json object as Base64 in byte slice

func (*Iterator) ReadBigFloat

func (iter *Iterator) ReadBigFloat() (ret *big.Float)

func (*Iterator) ReadBigInt

func (iter *Iterator) ReadBigInt() (ret *big.Int)

func (*Iterator) ReadBool

func (iter *Iterator) ReadBool() (ret bool)

ReadBool reads a json object as Bool

func (*Iterator) ReadFloat32

func (iter *Iterator) ReadFloat32() (ret float32)

func (*Iterator) ReadFloat64

func (iter *Iterator) ReadFloat64() (ret float64)

func (*Iterator) ReadInt

func (iter *Iterator) ReadInt() int

func (*Iterator) ReadInt16

func (iter *Iterator) ReadInt16() (ret int16)

func (*Iterator) ReadInt32

func (iter *Iterator) ReadInt32() (ret int32)

func (*Iterator) ReadInt64

func (iter *Iterator) ReadInt64() (ret int64)

func (*Iterator) ReadInt8

func (iter *Iterator) ReadInt8() (ret int8)

func (*Iterator) ReadMapCB

func (iter *Iterator) ReadMapCB(callback func(*Iterator, string) bool) bool

func (*Iterator) ReadNil

func (iter *Iterator) ReadNil() (ret bool)

ReadNil reads a json object as nil and returns whether it's a nil or not

func (*Iterator) ReadObject

func (iter *Iterator) ReadObject() (ret string)

func (*Iterator) ReadObjectCB

func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool

func (*Iterator) ReadString

func (iter *Iterator) ReadString() (ret string)

func (*Iterator) ReadStringAsSlice

func (iter *Iterator) ReadStringAsSlice() (ret []byte)

func (*Iterator) ReadUint

func (iter *Iterator) ReadUint() uint

func (*Iterator) ReadUint16

func (iter *Iterator) ReadUint16() (ret uint16)

func (*Iterator) ReadUint32

func (iter *Iterator) ReadUint32() (ret uint32)

func (*Iterator) ReadUint64

func (iter *Iterator) ReadUint64() uint64

func (*Iterator) ReadUint8

func (iter *Iterator) ReadUint8() (ret uint8)

func (*Iterator) ReadVal

func (iter *Iterator) ReadVal(obj interface{})

Read converts an Iterator instance into go interface, same as json.Unmarshal

func (*Iterator) Reset

func (iter *Iterator) Reset(reader io.Reader) *Iterator

Reset can reset an Iterator instance for another json buffer in io.Reader

func (*Iterator) ResetBytes

func (iter *Iterator) ResetBytes(input []byte) *Iterator

ResetBytes can reset an Iterator instance for another json byte slice

func (*Iterator) Skip

func (iter *Iterator) Skip()

Skip skips a json object and positions to relatively the next json object

func (*Iterator) SkipAndReturnBytes

func (iter *Iterator) SkipAndReturnBytes() []byte

func (*Iterator) WhatIsNext

func (iter *Iterator) WhatIsNext() ValueType

WhatIsNext gets ValueType of relatively next json object

type Stream

type Stream struct {
	Error error
	// contains filtered or unexported fields
}

func NewStream

func NewStream(cfg *frozenConfig, out io.Writer, bufSize int) *Stream

func (*Stream) Available

func (b *Stream) Available() int

Available returns how many bytes are unused in the buffer.

func (*Stream) Buffer

func (b *Stream) Buffer() []byte

func (*Stream) Buffered

func (b *Stream) Buffered() int

Buffered returns the number of bytes that have been written into the current buffer.

func (*Stream) Flush

func (b *Stream) Flush() error

Flush writes any buffered data to the underlying io.Writer.

func (*Stream) Reset

func (b *Stream) Reset(out io.Writer)

func (*Stream) Write

func (b *Stream) Write(p []byte) (nn int, err error)

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.

func (*Stream) WriteArrayEnd

func (stream *Stream) WriteArrayEnd()

func (*Stream) WriteArrayStart

func (stream *Stream) WriteArrayStart()

func (*Stream) WriteBool

func (stream *Stream) WriteBool(val bool)

func (*Stream) WriteEmptyArray

func (stream *Stream) WriteEmptyArray()

func (*Stream) WriteEmptyObject

func (stream *Stream) WriteEmptyObject()

func (*Stream) WriteFalse

func (stream *Stream) WriteFalse()

func (*Stream) WriteFloat32

func (stream *Stream) WriteFloat32(val float32)

func (*Stream) WriteFloat32Lossy

func (stream *Stream) WriteFloat32Lossy(val float32)

func (*Stream) WriteFloat64

func (stream *Stream) WriteFloat64(val float64)

func (*Stream) WriteFloat64Lossy

func (stream *Stream) WriteFloat64Lossy(val float64)

func (*Stream) WriteInt

func (stream *Stream) WriteInt(val int)

func (*Stream) WriteInt16

func (stream *Stream) WriteInt16(nval int16)

func (*Stream) WriteInt32

func (stream *Stream) WriteInt32(nval int32)

func (*Stream) WriteInt64

func (stream *Stream) WriteInt64(nval int64)

func (*Stream) WriteInt8

func (stream *Stream) WriteInt8(nval int8)

func (*Stream) WriteMore

func (stream *Stream) WriteMore()

func (*Stream) WriteNil

func (stream *Stream) WriteNil()

func (*Stream) WriteObjectEnd

func (stream *Stream) WriteObjectEnd()

func (*Stream) WriteObjectField

func (stream *Stream) WriteObjectField(field string)

func (*Stream) WriteObjectStart

func (stream *Stream) WriteObjectStart()

func (*Stream) WriteRaw

func (b *Stream) WriteRaw(s string)

func (*Stream) WriteString

func (stream *Stream) WriteString(s string)

func (*Stream) WriteTrue

func (stream *Stream) WriteTrue()

func (*Stream) WriteUint

func (stream *Stream) WriteUint(val uint)

func (*Stream) WriteUint16

func (stream *Stream) WriteUint16(val uint16)

func (*Stream) WriteUint32

func (stream *Stream) WriteUint32(val uint32)

func (*Stream) WriteUint64

func (stream *Stream) WriteUint64(val uint64)

func (*Stream) WriteUint8

func (stream *Stream) WriteUint8(val uint8)

func (*Stream) WriteVal

func (stream *Stream) WriteVal(val interface{})

type ValueType

type ValueType int
const (
	Invalid ValueType = iota
	String
	Number
	Nil
	Bool
	Array
	Object
)

Directories

Path Synopsis
output_tests

Jump to

Keyboard shortcuts

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