Search and commands

↑ ↓ to select · Enter to open · Esc to close

Type to search packages.

sonic

v1.15.5
github.com/bytedance/sonic

Documentation

pkg.go.dev ↗

Table of contents

↓ to select · Enter to jump· Shift+Enter for source

31 matches

Top ↑

Constants

UseStdJSON (2 declarations)

const (
	// UseStdJSON indicates you are using fallback implementation (encoding/json)
	UseStdJSON = iota
	// UseSonicJSON indicates you are using real sonic implementation
	UseSonicJSON
)

APIKind

const APIKind = apiKind

APIKind is the kind of API, 0 is std json, 1 is sonic.

Variables

ConfigDefault (3 declarations)

var (
	// ConfigDefault is the default config of APIs, aiming at efficiency and safety.
	ConfigDefault = Config{}.Froze()

	// ConfigStd is the standard config of APIs, aiming at being compatible with encoding/json.
	ConfigStd = Config{
		EscapeHTML:       true,
		SortMapKeys:      true,
		CompactMarshaler: true,
		CopyString:       true,
		ValidateString:   true,
	}.Froze()

	// ConfigFastest is the fastest config of APIs, aiming at speed.
	ConfigFastest = Config{
		NoValidateJSONMarshaler: true,
		NoValidateJSONSkip:      true,
	}.Froze()
)

Functions

Get

func Get(src []byte, path ...interface{}) (ast.Node, error)

Get searches and locates the given path from src json, and returns a ast.Node representing the partially json.

Each path arg must be integer or string:

  • Integer is target index(>=0), means searching current node as array.
  • String is target key, means searching current node as object.

Notice: It expects the src json is **Well-formed** and **Immutable** when calling, otherwise it may return unexpected result. Considering memory safety, the returned JSON is **Copied** from the input

GetCopyFromString

func GetCopyFromString(src string, path ...interface{}) (ast.Node, error)

GetCopyFromString is same with Get except src is string

GetFromString

func GetFromString(src string, path ...interface{}) (ast.Node, error)

GetFromString is same with Get except src is string.

WARNING: The returned JSON is **Referenced** from the input. Caching or long-time holding the returned node may cause OOM. If your src is big, consider use GetFromStringCopy().

GetWithOptions

func GetWithOptions(src []byte, opts ast.SearchOptions, path ...interface{}) (ast.Node, error)

GetWithOptions searches and locates the given path from src json, with specific options of ast.Searcher

Marshal

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

Marshal returns the JSON encoding bytes of v.

MarshalIndent

func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)

MarshalIndent is like Marshal but applies Indent to format the output. Each JSON element in the output will begin on a new line beginning with prefix followed by one or more copies of indent according to the indentation nesting.

MarshalString

func MarshalString(val interface{}) (string, error)

MarshalString returns the JSON encoding string of v.

Pretouch

func Pretouch(vt reflect.Type, opts ...option.CompileOption) error

Pretouch compiles vt ahead-of-time to avoid JIT compilation on-the-fly, in order to reduce the first-hit latency.

Opts are the compile options, for example, "option.WithCompileRecursiveDepth" is a compile option to set the depth of recursive compile for the nested struct type.

PretouchMany

func PretouchMany(vts []reflect.Type, opts ...option.CompileOption) error

PretouchMany compiles all JIT types in single moduledata, to reduce the overhead of `findmoduledata`

Opts are the compile options, for example, "option.WithCompileRecursiveDepth" is a compile option to set the depth of recursive compile for the nested struct type.

Unmarshal

func Unmarshal(buf []byte, val interface{}) error

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. NOTICE: This API copies given buffer by default, if you want to pass JSON more efficiently, use UnmarshalString instead.

UnmarshalString

func UnmarshalString(buf string, val interface{}) error

UnmarshalString is like Unmarshal, except buf is a string.

Valid

func Valid(data []byte) bool

Valid reports whether data is a valid JSON encoding.

ValidString

func ValidString(data string) bool

Valid reports whether data is a valid JSON encoding.

Types

API

type API interface {
	// MarshalToString returns the JSON encoding string of v
	MarshalToString(v interface{}) (string, error)
	// Marshal returns the JSON encoding bytes of v.
	Marshal(v interface{}) ([]byte, error)
	// MarshalIndent returns the JSON encoding bytes with indent and prefix.
	MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
	// UnmarshalFromString parses the JSON-encoded bytes and stores the result in the value pointed to by v.
	UnmarshalFromString(str string, v interface{}) error
	// Unmarshal parses the JSON-encoded string and stores the result in the value pointed to by v.
	Unmarshal(data []byte, v interface{}) error
	// NewEncoder create a Encoder holding writer
	NewEncoder(writer io.Writer) Encoder
	// NewDecoder create a Decoder holding reader
	NewDecoder(reader io.Reader) Decoder
	// Valid validates the JSON-encoded bytes and reports if it is valid
	Valid(data []byte) bool
}

API is a binding of specific config. This interface is inspired by github.com/json-iterator/go, and has same behaviors under equivalent config.

Config

type Config struct {
	// EscapeHTML indicates encoder to escape all HTML characters
	// after serializing into JSON (see https://pkg.go.dev/encoding/json#HTMLEscape).
	// WARNING: This hurts performance A LOT, USE WITH CARE.
	EscapeHTML bool

	// SortMapKeys indicates encoder that the keys of a map needs to be sorted
	// before serializing into JSON.
	// WARNING: This hurts performance A LOT, USE WITH CARE.
	SortMapKeys bool

	// CompactMarshaler indicates encoder that the output JSON from json.Marshaler
	// is always compact and needs no validation
	CompactMarshaler bool

	// NoQuoteTextMarshaler indicates encoder that the output text from encoding.TextMarshaler
	// is always escaped string and needs no quoting
	NoQuoteTextMarshaler bool

	// NoNullSliceOrMap indicates encoder that all empty Array or Object are encoded as '[]' or '{}',
	// instead of 'null'
	NoNullSliceOrMap bool

	// UseInt64 indicates decoder to unmarshal an integer into an interface{} as an
	// int64 instead of as a float64.
	UseInt64 bool

	// UseNumber indicates decoder to unmarshal a number into an interface{} as a
	// json.Number instead of as a float64.
	UseNumber bool

	// UseUnicodeErrors indicates decoder to return an error when encounter invalid
	// UTF-8 escape sequences.
	UseUnicodeErrors bool

	// DisallowUnknownFields indicates 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.
	DisallowUnknownFields bool

	// CopyString indicates decoder to decode string values by copying instead of referring.
	CopyString bool

	// ValidateString indicates decoder and encoder to validate string values: decoder will return errors
	// when unescaped control chars(\u0000-\u001f) in the string value of JSON.
	ValidateString bool

	// NoValidateJSONMarshaler indicates that the encoder should not validate the output string
	// after encoding the JSONMarshaler to JSON.
	NoValidateJSONMarshaler bool

	// NoValidateJSONSkip indicates the decoder should not validate the JSON value when skipping it,
	// such as unknown-fields, mismatched-type, redundant elements..
	NoValidateJSONSkip bool

	// NoEncoderNewline indicates that the encoder should not add a newline after every message
	NoEncoderNewline bool

	// Encode Infinity or Nan float into `null`, instead of returning an error.
	EncodeNullForInfOrNan bool

	// CaseSensitive indicates that the decoder should not ignore the case of object keys.
	CaseSensitive bool
}

Config is a combination of sonic/encoder.Options and sonic/decoder.Options

Config.Froze

func (cfg Config) Froze() API

Froze convert the Config to API

Decoder

type Decoder interface {
	// Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.
	Decode(val interface{}) error
	// Buffered returns a reader of the data remaining in the Decoder's buffer.
	// The reader is valid until the next call to Decode.
	Buffered() io.Reader
	// 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.
	DisallowUnknownFields()
	// More reports whether there is another element in the current array or object being parsed.
	More() bool
	// UseNumber causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.
	UseNumber()
}

Decoder decodes JSON from io.Read

Encoder

type Encoder interface {
	// Encode writes the JSON encoding of v to the stream, followed by a newline character.
	Encode(val interface{}) error
	// SetEscapeHTML specifies whether problematic HTML characters
	// should be escaped inside JSON quoted strings.
	// The default behavior NOT ESCAPE
	SetEscapeHTML(on bool)
	// SetIndent instructs the encoder to format each subsequent encoded value
	// as if indented by the package-level function Indent(dst, src, prefix, indent).
	// Calling SetIndent("", "") disables indentation
	SetIndent(prefix, indent string)
}

Encoder encodes JSON into io.Writer

NoCopyRawMessage

type NoCopyRawMessage []byte

NoCopyRawMessage is a NOCOPY raw encoded JSON value. It implements [Marshaler] and [Unmarshaler] and can be used to delay JSON decoding or precompute a JSON encoding.

NoCopyRawMessage.MarshalJSON

func (m NoCopyRawMessage) MarshalJSON() ([]byte, error)

MarshalJSON returns m as the JSON encoding of m.

NoCopyRawMessage.UnmarshalJSON

func (m *NoCopyRawMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON sets *m to a reference of data. NoCopy here!!!

Dependency graph