json

package
v0.1.0-alpha.4 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package json encodes and decodes JSON with the API and the results of encoding/json, written for speed and low memory use.

It has the API of encoding/json in Go 1.26 and the results of the encoding/json it is built with: the same bytes from Marshal, the same values from Unmarshal and the same errors. That is the classic encoding/json, or the one built on encoding/json/v2, as it is by default from Go 1.27 and with GOEXPERIMENT=jsonv2 from Go 1.25.

RawMessage, Number, Marshaler, Unmarshaler, Delim, Token and the error types are aliases of encoding/json's, so values, type switches and errors.As work across both packages.

The one addition is UnmarshalNoCopy, which stores strings that view the input instead of copies, for callers that keep the input unchanged while they use the decoded values.

Differences that do not change results:

  • Marshal of a value nested more than 1<<20 levels deep (not a cycle) returns an *UnsupportedValueError. encoding/json recurses until the goroutine stack overflows, which ends the process.
  • Short strings, RawMessage copies, small scalars behind pointers and the strings and numbers held by interface values that Unmarshal stores share small blocks of at most 4 KiB per call. Keeping one such value keeps its block alive; encoding/json keeps only the value itself.
  • A Decoder whose reader can seek, such as an *os.File, reads a value longer than 128 KiB twice: once to check it and once to decode it, with long strings read directly into their own allocations. It holds the decoded value and a window of 256 KiB, not the input. Code that watches the calls on the reader sees the extra reads and seeks, and what Buffered returns after such a value is empty. If the input changes between the two reads, Decode returns an error, the value may be partly set, and the Decoder stops.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Compact

func Compact(dst *bytes.Buffer, src []byte) error

Compact appends to dst the JSON-encoded src with insignificant space characters elided.

func HTMLEscape

func HTMLEscape(dst *bytes.Buffer, src []byte)

HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 so that the JSON will be safe to embed inside HTML <script> tags. For historical reasons, web browsers don't honor standard HTML escaping within <script> tags, so an alternative JSON encoding must be used.

func Indent

func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error

Indent appends to dst an indented form of the JSON-encoded src. Each element in a JSON object or array begins on a new, indented line beginning with prefix followed by one or more copies of indent according to the indentation nesting. The data appended to dst does not begin with the prefix nor any indentation, to make it easier to embed inside other formatted JSON data. Although leading space characters (space, tab, carriage return, newline) at the beginning of src are dropped, trailing space characters at the end of src are preserved and copied to dst. For example, if src has no trailing spaces, neither will dst; if src ends in a trailing newline, so will dst.

func Marshal

func Marshal(v any) ([]byte, error)

Marshal returns the JSON encoding of v. It follows the rules of encoding/json.Marshal and gives the same bytes and errors, except that a value nested more than 1<<20 levels deep returns an UnsupportedValueError, where encoding/json overflows the stack.

func MarshalIndent

func MarshalIndent(v any, 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.

func Unmarshal

func Unmarshal(data []byte, v any) error

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError. It follows the rules of encoding/json.Unmarshal and gives the same results and errors.

The whole input is validated before v is modified, so on a syntax error v is unchanged.

func UnmarshalNoCopy

func UnmarshalNoCopy(data []byte, v any) error

UnmarshalNoCopy is Unmarshal, except that the values it stores may share memory with data: a string, map key or Number whose JSON text needs no unescaping, and a RawMessage, view data instead of holding a copy. The caller must not modify data while any of them is in use.

A RawMessage is set to view data, without reusing the memory it held.

func Valid

func Valid(data []byte) bool

Valid reports whether data is a valid JSON encoding.

Types

type Decoder

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

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

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder that reads from r.

The decoder introduces its own buffering and may read data from r beyond the JSON values requested.

func (*Decoder) Buffered

func (dec *Decoder) Buffered() io.Reader

Buffered returns a reader of the data remaining in the Decoder's buffer. The reader is valid until the next call to Decode.

func (*Decoder) Decode

func (dec *Decoder) Decode(v any) 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) DisallowUnknownFields

func (dec *Decoder) DisallowUnknownFields()

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.

func (*Decoder) InputOffset

func (dec *Decoder) InputOffset() int64

InputOffset returns the input stream byte offset of the current decoder position. The offset gives the location of the end of the most recently returned token and the beginning of the next token.

func (*Decoder) More

func (dec *Decoder) More() bool

More reports whether there is another element in the current array or object being parsed.

func (*Decoder) Token

func (dec *Decoder) Token() (Token, error)

Token returns the next JSON token in the input stream. At the end of the input stream, Token returns nil, io.EOF.

Token guarantees that the delimiters [ ] { } it returns are properly nested and matched: if Token encounters an unexpected delimiter in the input, it will return an error.

The input stream consists of basic JSON values—bool, string, number, and null—along with delimiters [ ] { } of type Delim to mark the start and end of arrays and objects. Commas and colons are elided.

func (*Decoder) UseNumber

func (dec *Decoder) UseNumber()

UseNumber causes the Decoder to unmarshal a number into an interface value as a Number instead of as a float64.

type Delim

type Delim = stdjson.Delim

A Delim is a JSON array or object delimiter, one of [ ] { or }.

type Encoder

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

An Encoder writes JSON values to an output stream.

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that writes to w.

func (*Encoder) Encode

func (enc *Encoder) Encode(v any) error

Encode writes the JSON encoding of v to the stream, with insignificant space characters elided, followed by a newline character.

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

func (*Encoder) SetEscapeHTML

func (enc *Encoder) SetEscapeHTML(on bool)

SetEscapeHTML specifies whether problematic HTML characters should be escaped inside JSON quoted strings. The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML.

In non-HTML settings where the escaping interferes with the readability of the output, SetEscapeHTML(false) disables this behavior.

func (*Encoder) SetIndent

func (enc *Encoder) SetIndent(prefix, indent string)

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.

type InvalidUTF8Error deprecated

type InvalidUTF8Error = stdjson.InvalidUTF8Error

Before Go 1.2, an InvalidUTF8Error was returned by Marshal when attempting to encode a string value with invalid UTF-8 sequences. As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by replacing invalid bytes with the Unicode replacement rune U+FFFD.

Deprecated: No longer used; kept for compatibility.

type InvalidUnmarshalError

type InvalidUnmarshalError = stdjson.InvalidUnmarshalError

An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.

type Marshaler

type Marshaler = stdjson.Marshaler

Marshaler is implemented by types that can marshal themselves into valid JSON.

type MarshalerError

type MarshalerError = stdjson.MarshalerError

A MarshalerError represents an error from calling a MarshalJSON or MarshalText method.

type Number

type Number = stdjson.Number

A Number represents a JSON number literal. See encoding/json.Number.

type RawMessage

type RawMessage = stdjson.RawMessage

RawMessage is a raw encoded JSON value. See encoding/json.RawMessage.

type SyntaxError

type SyntaxError = stdjson.SyntaxError

A SyntaxError is a description of a JSON syntax error.

type Token

type Token = stdjson.Token

A Token holds a value of one of these types: Delim, bool, float64, Number, string, nil.

type UnmarshalFieldError deprecated

type UnmarshalFieldError = stdjson.UnmarshalFieldError

An UnmarshalFieldError describes a JSON object key that led to an unexported (and therefore unwritable) struct field.

Deprecated: No longer used; kept for compatibility.

type UnmarshalTypeError

type UnmarshalTypeError = stdjson.UnmarshalTypeError

An UnmarshalTypeError describes a JSON value that was not appropriate for a value of a specific Go type.

type Unmarshaler

type Unmarshaler = stdjson.Unmarshaler

Unmarshaler is implemented by types that can unmarshal a JSON description of themselves.

type UnsupportedTypeError

type UnsupportedTypeError = stdjson.UnsupportedTypeError

An UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type.

type UnsupportedValueError

type UnsupportedValueError = stdjson.UnsupportedValueError

An UnsupportedValueError is returned by Marshal when attempting to encode an unsupported value.

Jump to

Keyboard shortcuts

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