Help us shape the future of Go! Take the 2026 Go Developer Survey

jsontext

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package jsontext reads and writes the syntax of JSON, as RFC 4627, RFC 7159, RFC 7493, RFC 8259 and RFC 8785 specify it. It is a drop-in replacement of encoding/json/jsontext: its API and behavior are the ones of the package of Go 1.27, on any version of Go.

An Encoder writes, and a Decoder reads, a stream of JSON tokens and values.

Tokens and Values

A JSON token is one of the elements of the structure of JSON:

  • a JSON literal (i.e., null, true, or false)
  • a JSON string (e.g., "hello, world!")
  • a JSON number (e.g., 123.456)
  • a begin or end delimiter of a JSON object (i.e., '{' or '}')
  • a begin or end delimiter of a JSON array (i.e., '[' or ']')

The Token type holds a token. The commas and colons are structural characters too, but no Token holds them: the grammar implies where they are, such as the colon between the name and the value of a member of an object.

A JSON value is a whole unit of JSON:

  • a JSON literal, string, or number
  • a JSON object (e.g., `{"name":"value"}`)
  • a JSON array (e.g., `[1,2,3]`)

The Value type holds a value, as the raw text of it. Literals, strings and numbers are both tokens and values; only a value holds a whole object or array.

The methods of Encoder and Decoder write or read the next Token or Value of a stream, and check with a state machine that the stream is valid JSON. Options passed to NewEncoder and NewDecoder configure them.

Terminology

"Encode" and "decode" are about the syntax of JSON, which this package deals with, and "marshal" and "unmarshal" about the meaning of JSON values as Go values, which encoding/json/v2 deals with. A stream of tokens can be encoded or decoded without any Go value which represents it.

This package uses the terms of JSON:

  • an "object" is an unordered collection of members, each a name and a value.
  • an "array" is an ordered sequence of elements.
  • a "value" is a literal (i.e., null, false, or true), a string, a number, an object, or an array.

See RFC 8259.

Specifications

The RFCs are, in the order of their strictness:

  • RFC 4627 and RFC 7159 recommend, but don't require, UTF-8 and unique names in an object.
  • RFC 8259 requires UTF-8, and recommends unique names.
  • RFC 7493 requires UTF-8 and unique names.
  • RFC 8785 defines a canonical form: UTF-8, unique names in a specified order, and exact formats of the strings and numbers.

RFC 4627 restricts the top-level values to objects and arrays; the later RFCs allow any value there.

By default, this package operates as RFC 7493 specifies, which is stricter than RFC 8259 and fully complies with it: it chooses a behavior where RFC 8259 leaves one undefined, for interoperability. Options configure it to operate as another RFC specifies.

Index

Constants

This section is empty.

Variables

View Source
var (
	Null  = Token{/* contains filtered or unexported fields */}
	False = Token{/* contains filtered or unexported fields */}
	True  = Token{/* contains filtered or unexported fields */}

	BeginObject = Token{/* contains filtered or unexported fields */}
	EndObject   = Token{/* contains filtered or unexported fields */}
	BeginArray  = Token{/* contains filtered or unexported fields */}
	EndArray    = Token{/* contains filtered or unexported fields */}
)
View Source
var ErrDuplicateName = ierrors.ErrDuplicateName

ErrDuplicateName reports that a JSON token could not be encoded or decoded because its name is already the name of another member of the same JSON object. It is wrapped directly by a SyntacticError, whose JSONPointer points to the duplicate name:

var serr *jsontext.SyntacticError
if errors.As(err, &serr) && serr.Err == jsontext.ErrDuplicateName {
	ptr := serr.JSONPointer // JSON pointer to the duplicate member
	name := ptr.LastToken() // the name itself
	...
}

It is only reported if AllowDuplicateNames is false.

View Source
var ErrNonStringName = ierrors.ErrNonStringName

ErrNonStringName reports that a JSON token could not be encoded or decoded because it is not a string where a JSON object name is, which RFC 8259, section 4, requires to be a string. It is wrapped directly by a SyntacticError.

Functions

func AppendFloat

func AppendFloat(dst []byte, src float64, bits int) []byte

AppendFloat appends src to dst as a JSON number of RFC 8259, section 6, with bits of precision.

Except for -0, which it writes as -0, it writes a number as ECMA-262, 10th edition, section 7.1.12.1 does, and, with 64 bits, as RFC 8785, section 3.2.2.3 does. NaN, +Inf and -Inf are written as NaN, +Inf and -Inf.

Most JSON libraries and standards take JSON numbers as 64-bit floating-point numbers: use 64 bits of precision unless the reader of the number knows that it has 32 bits of precision.

func AppendFormat

func AppendFormat[Bytes ~[]byte | ~string](dst []byte, src Bytes, opts ...Options) ([]byte, error)

AppendFormat appends the JSON value src to dst, formatted as the options say. See Value.Format for how it formats values.

dst and src may overlap. At an error, all of src is appended to dst.

func AppendQuote

func AppendQuote[Bytes ~[]byte | ~string](dst []byte, src Bytes) ([]byte, error)

AppendQuote appends src to dst as a JSON string, in its minimal form of RFC 8785, section 3.2.2.2, and returns the extended buffer. Invalid UTF-8 is appended as the Unicode replacement character, and reported by an error at the end. dst must not overlap src.

func AppendUnquote

func AppendUnquote[Bytes ~[]byte | ~string](dst []byte, src Bytes) ([]byte, error)

AppendUnquote appends the value of the JSON string src to dst and returns the extended buffer. src must be a JSON string, without white space around it. Invalid UTF-8 is appended as the Unicode replacement character, and reported by an error at the end. Bytes after the string are an error. dst must not overlap src.

Types

type Decoder

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

Decoder is a streaming decoder of raw JSON tokens and values. It reads a stream of top-level JSON values, separated by optional white space.

Decoder.ReadToken and Decoder.ReadValue calls may be interleaved. For example, the JSON value

{"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}}

can be read by these calls (ignoring errors):

d.ReadToken() // {
d.ReadToken() // "name"
d.ReadToken() // "value"
d.ReadValue() // "array"
d.ReadToken() // [
d.ReadToken() // null
d.ReadToken() // false
d.ReadValue() // true
d.ReadToken() // 3.14159
d.ReadToken() // ]
d.ReadValue() // "object"
d.ReadValue() // {"k":"v"}
d.ReadToken() // }

which is one of many sequences of calls which read it.

func NewDecoder

func NewDecoder(r io.Reader, opts ...Options) *Decoder

NewDecoder constructs a streaming decoder which reads from r.

If r is a bytes.Buffer, the decoder reads the buffer in place, without copying its contents. The buffer must not be written to while the decoder is used.

func (*Decoder) InputOffset

func (d *Decoder) InputOffset() int64

InputOffset returns the offset in the input after the last token or value which was read. The decoder may have read more of the input into its buffer.

func (*Decoder) Options

func (d *Decoder) Options() Options

Options returns the options of the decoder: the ones it was constructed or last reset with, which follow a later Reset.

func (*Decoder) PeekKind

func (d *Decoder) PeekKind() Kind

PeekKind returns the kind of the next token, without reading it.

It returns KindInvalid at an error, which it keeps for the next read call to report: a PeekKind call must be followed by a read call.

func (*Decoder) ReadToken

func (d *Decoder) ReadToken() (Token, error)

ReadToken reads the next Token and advances the read offset. The token is only valid until the next Peek, Read or Skip call. It returns io.EOF at the end of the input.

func (*Decoder) ReadValue

func (d *Decoder) ReadValue() (Value, error)

ReadValue returns the next raw JSON value and advances the read offset. The value has no leading and trailing white space, and holds the exact bytes of the input, which may contain invalid UTF-8 if AllowInvalidUTF8 is set.

The value is only valid until the next Peek, Read or Skip call, and must not be changed while the decoder is used. If the next token is the end of an object or array, it reports a SyntacticError and doesn't change the state of the decoder. It returns io.EOF at the end of the input.

func (*Decoder) Reset

func (d *Decoder) Reset(r io.Reader, opts ...Options)

Reset resets the decoder to read from r anew, with the options.

func (*Decoder) SkipValue

func (d *Decoder) SkipValue() error

SkipValue skips the next value. An object or array is read token by token, as ReadToken reads it, so that at an error the decoder is where the error is; another value is read as ReadValue reads it.

func (*Decoder) StackDepth

func (d *Decoder) StackDepth() int

StackDepth returns the number of the objects and arrays which are open in the input which was read: 0 at the top level, before any token, after a top-level value and between top-level values, 1 in a top-level object or array, and so on.

func (*Decoder) StackIndex

func (d *Decoder) StackIndex(i int) (Kind, int64)

StackIndex returns the kind and the length of the level i of the stack, which is from 0 to Decoder.StackDepth: KindInvalid for the level 0, KindBeginObject for an object, KindBeginArray for an array. The length of an object counts its names and values: a complete object has an even length.

func (*Decoder) StackPointer

func (d *Decoder) StackPointer() Pointer

StackPointer returns a JSON Pointer (RFC 6901) to the last value which was read.

func (*Decoder) UnreadBuffer

func (d *Decoder) UnreadBuffer() []byte

UnreadBuffer returns the input in the buffer of the decoder which was read from the reader but not by Decoder.ReadToken or Decoder.ReadValue: it may be any number of bytes, which may not be valid JSON. How much input the decoder buffers may change over time.

The input after the last token or value is this buffer followed by the rest of the reader.

The buffer must not be changed while the decoder is used, and is valid until the next Peek, Read or Skip call.

type Encoder

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

Encoder is a streaming encoder of raw JSON tokens and values. It writes a stream of top-level JSON values, each followed by a line feed.

Encoder.WriteToken and Encoder.WriteValue calls may be interleaved. For example, the JSON value

{"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}}

can be written by these calls (ignoring errors):

e.WriteToken(BeginObject)        // {
e.WriteToken(String("name"))     // "name"
e.WriteToken(String("value"))    // "value"
e.WriteValue(Value(`"array"`))   // "array"
e.WriteToken(BeginArray)         // [
e.WriteToken(Null)               // null
e.WriteToken(False)              // false
e.WriteValue(Value("true"))      // true
e.WriteToken(Float(3.14159))     // 3.14159
e.WriteToken(EndArray)           // ]
e.WriteValue(Value(`"object"`))  // "object"
e.WriteValue(Value(`{"k":"v"}`)) // {"k":"v"}
e.WriteToken(EndObject)          // }

which is one of many sequences of calls which write it.

func NewEncoder

func NewEncoder(w io.Writer, opts ...Options) *Encoder

NewEncoder constructs a streaming encoder which writes to w, with the options. It writes its buffer to w when the buffer is full enough, or when a top-level value is complete.

If w is a bytes.Buffer, the encoder appends to the buffer directly, without copying the output from a buffer of its own.

func (*Encoder) AvailableBuffer

func (e *Encoder) AvailableBuffer() []byte

AvailableBuffer returns an empty buffer which may have room, to build a Value for the next call of Encoder.WriteValue:

b := e.AvailableBuffer()
b = append(b, '"')
b = appendString(b, v) // append the string formatting of v
b = append(b, '"')
... := e.WriteValue(b)

WriteValue takes a valid JSON value: a Value built as raw bytes takes more care than a Token of a constructor such as String.

func (*Encoder) Options

func (e *Encoder) Options() Options

Options returns the options of the encoder: the ones it was constructed or last reset with, and, for Multiline, the space after a colon and the indentation it takes if they are not set. They follow a later Reset.

func (*Encoder) OutputOffset

func (e *Encoder) OutputOffset() int64

OutputOffset returns the offset in the output after the last token or value which was written. The encoder may not have written all of it to the writer yet.

func (*Encoder) Reset

func (e *Encoder) Reset(w io.Writer, opts ...Options)

Reset resets the encoder to write to w anew, with the options.

func (*Encoder) StackDepth

func (e *Encoder) StackDepth() int

StackDepth returns the number of the objects and arrays which are open in the output: 0 at the top level, before any token, after a top-level value and between top-level values, 1 in a top-level object or array, and so on.

func (*Encoder) StackIndex

func (e *Encoder) StackIndex(i int) (Kind, int64)

StackIndex returns the kind and the length of the level i of the stack, which is from 0 to Encoder.StackDepth: KindInvalid for the level 0, KindBeginObject for an object, KindBeginArray for an array. The length of an object counts its names and values: a complete object has an even length.

func (*Encoder) StackPointer

func (e *Encoder) StackPointer() Pointer

StackPointer returns a JSON Pointer (RFC 6901) to the last value which was written.

func (*Encoder) WriteToken

func (e *Encoder) WriteToken(t Token) error

WriteToken writes the next token and advances the write offset.

The token must fit the grammar: a number where the encoder needs an object name, which is always a string, or the end of an object where an array ends, is an error. At an invalid token, it reports a SyntacticError, and the state of the encoder doesn't change: the offset of the error is Encoder.OutputOffset plus the delimiters and white space which would precede the token.

func (*Encoder) WriteValue

func (e *Encoder) WriteValue(v Value) error

WriteValue writes the next raw value and advances the write offset. The encoder checks that the value is valid, and formats its white space and strings as the options say. With AllowInvalidUTF8, invalid UTF-8 is mangled as the Unicode replacement character, U+FFFD.

The value must fit the grammar (see the examples of Encoder.WriteToken). At an invalid value, it reports a SyntacticError, and the state of the encoder doesn't change: the offset of the error is Encoder.OutputOffset plus the offset of the error in v.

type Kind

type Kind byte

Kind is the kind of a JSON token.

It is a single byte, the first byte of the token in the grammar, except for numbers, whose kind is always '0'.

const (
	KindInvalid     Kind = 0   // invalid kind
	KindNull        Kind = 'n' // null
	KindFalse       Kind = 'f' // false
	KindTrue        Kind = 't' // true
	KindString      Kind = '"' // string
	KindNumber      Kind = '0' // number
	KindBeginObject Kind = '{' // begin object
	KindEndObject   Kind = '}' // end object
	KindBeginArray  Kind = '[' // begin array
	KindEndArray    Kind = ']' // end array
)

func (Kind) String

func (k Kind) String() string

String returns a string representation of k.

type Options

type Options = options.Options

Options configures NewEncoder, Encoder.Reset, NewDecoder and Decoder.Reset, and the functions and methods which format values. Each takes a list of options, in which an option set later overrides a property set by an earlier one.

A single Options type is used for encoding and decoding: an option which affects only one of them is ignored by the other. It is the same type as the Options of github.com/goccy/go-json/v2 and of github.com/goccy/go-json.

  • AllowDuplicateNames affects encoding and decoding
  • AllowInvalidUTF8 affects encoding and decoding
  • EscapeForHTML affects encoding only
  • EscapeForJS affects encoding only
  • PreserveRawStrings affects encoding only
  • CanonicalizeRawInts affects encoding only
  • CanonicalizeRawFloats affects encoding only
  • ReorderRawObjects affects encoding only
  • SpaceAfterColon affects encoding only
  • SpaceAfterComma affects encoding only
  • Multiline affects encoding only
  • WithIndent affects encoding only
  • WithIndentPrefix affects encoding only

func AllowDuplicateNames

func AllowDuplicateNames(v bool) Options

AllowDuplicateNames specifies that JSON objects may contain duplicate member names. Disabling the check of duplicate names may make encoding and decoding faster, but breaks compliance with RFC 7493, section 2.3. The input or output still complies with RFC 8259, which leaves the handling of duplicate names unspecified.

This affects encoding and decoding.

func AllowInvalidUTF8

func AllowInvalidUTF8(v bool) Options

AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8, which is mangled as the Unicode replacement character, U+FFFD. This breaks compliance with RFC 7493, section 2.1, and RFC 8259, section 8.1.

This affects encoding and decoding.

func CanonicalizeRawFloats

func CanonicalizeRawFloats(v bool) Options

CanonicalizeRawFloats specifies that a raw JSON floating-point number (a number with a fraction or an exponent) in a Token or a Value is written in the canonical form of RFC 8785, section 3.2.2.3; -0 is written as 0.

The numbers are IEEE 754 double precision numbers. A single precision number which is canonicalized is read back as the same single precision number. A number beyond ±1.7976931348623157e+308, the largest finite number, is saturated at it.

This affects encoding only.

func CanonicalizeRawInts

func CanonicalizeRawInts(v bool) Options

CanonicalizeRawInts specifies that a raw JSON integer (a number without a fraction and an exponent) in a Token or a Value is written in the canonical form of RFC 8785, section 3.2.2.3; -0 is written as 0.

The numbers are IEEE 754 double precision numbers: an integer which needs more precision loses it. For example, integers beyond ±2⁵³ lose their precision: 1234567890123456789 is written as 1234567890123456800.

This affects encoding only.

func EscapeForHTML

func EscapeForHTML(v bool) Options

EscapeForHTML specifies that the characters '<', '>' and '&' in JSON strings are escaped as hexadecimal Unicode code points (e.g., <), so that the output is safe to embed within HTML.

This affects encoding only.

func EscapeForJS

func EscapeForJS(v bool) Options

EscapeForJS specifies that the characters U+2028 and U+2029 in JSON strings are escaped as hexadecimal Unicode code points (e.g., 
), so that the output is valid to embed within JavaScript. See RFC 8259, section 12.

This affects encoding only.

func Multiline

func Multiline(v bool) Options

Multiline specifies that the output is written on multiple lines: every JSON object member and array element is on a new line, indented by its depth.

Unless they are specified, SpaceAfterColon is true, SpaceAfterComma is false, and the indentation of WithIndent is "\t".

If it is false, the output is a single line, whose only white space is the one of SpaceAfterColon and SpaceAfterComma.

This affects encoding only.

func PreserveRawStrings

func PreserveRawStrings(v bool) Options

PreserveRawStrings specifies that the escape sequences of a raw JSON string in a Token or a Value are written as they are. The characters which EscapeForHTML and EscapeForJS escape are still escaped. If AllowInvalidUTF8 is set, the bytes of invalid UTF-8 are written as they are too.

This affects encoding only.

func ReorderRawObjects

func ReorderRawObjects(v bool) Options

ReorderRawObjects specifies that the members of a raw JSON object in a Value are written in the order of RFC 8785, section 3.2.3.

This affects encoding only.

func SpaceAfterColon

func SpaceAfterColon(v bool) Options

SpaceAfterColon specifies that a space is written after the colon which follows a JSON object name.

This affects encoding only.

func SpaceAfterComma

func SpaceAfterComma(v bool) Options

SpaceAfterComma specifies that a space is written after the comma which follows a JSON object value or array element.

This affects encoding only.

func WithIndent

func WithIndent(indent string) Options

WithIndent specifies that the output is written on multiple lines, where each JSON object member and array element starts a line with the prefix of WithIndentPrefix and then indent once for each level of nesting. The indent must consist of spaces and tabs only.

To write multiline output without a preference for the indentation, use Multiline.

This affects encoding only. It implies Multiline(true).

func WithIndentPrefix

func WithIndentPrefix(prefix string) Options

WithIndentPrefix specifies that the output is written on multiple lines, where each JSON object member and array element starts a line with prefix and then the indentation of WithIndent once for each level of nesting. The prefix must consist of spaces and tabs only.

This affects encoding only. It implies Multiline(true).

type Pointer

type Pointer string

Pointer is a JSON Pointer (RFC 6901), which references a JSON value relative to the root of the top-level JSON value.

It is a list of tokens, each after a slash: a JSON object name, or the index of a JSON array element as a base-10 integer. An array index and an object name which is an integer can't be told apart without the structure of the value which the pointer refers to.

A value has exactly one pointer, so two pointers are equal if and only if they point to the same value.

func (Pointer) AppendToken

func (p Pointer) AppendToken(tok string) Pointer

AppendToken appends the token tok to p and returns the pointer.

func (Pointer) Contains

func (p Pointer) Contains(pc Pointer) bool

Contains reports whether the JSON value which p points to is the one which pc points to or contains it.

func (Pointer) IsValid

func (p Pointer) IsValid() bool

IsValid reports whether p is a valid JSON Pointer of RFC 6901. The concatenation of two valid pointers is a valid pointer.

func (Pointer) LastToken

func (p Pointer) LastToken() string

LastToken returns the last token of p. The last token of the empty pointer is the empty string.

func (Pointer) Parent

func (p Pointer) Parent() Pointer

Parent returns p without its last token. The parent of the empty pointer is the empty pointer.

func (Pointer) Tokens

func (p Pointer) Tokens() iter.Seq[string]

Tokens returns an iterator over the tokens of p, from the first to the last.

type SyntacticError

type SyntacticError struct {

	// ByteOffset is the offset in the input or output at or after which the error occurred.
	ByteOffset int64
	// JSONPointer points to the JSON value within which the error occurred (see RFC 6901).
	JSONPointer Pointer

	// Err is the underlying error.
	Err error
	// contains filtered or unexported fields
}

SyntacticError describes an error of the JSON grammar found while encoding or decoding.

The contents of this error, as this package makes it, may change over time.

func (*SyntacticError) Error

func (e *SyntacticError) Error() string

func (*SyntacticError) Unwrap

func (e *SyntacticError) Unwrap() error

type Token

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

Token is a lexical JSON token, one of:

  • a JSON literal (i.e., null, true, or false)
  • a JSON string (e.g., "hello, world!")
  • a JSON number (e.g., 123.456)
  • a begin or end delimiter of a JSON object (i.e., { or } )
  • a begin or end delimiter of a JSON array (i.e., [ or ] )

A Token can't hold a whole array or object, which a Value can. There is no Token for a comma or a colon, which the structure implies.

A Token holds its value in one of two forms:

  • As raw JSON text in the buffer of a Decoder, as only Decoder.ReadToken makes it. Such a token is only valid until the next call of a method of the Decoder (e.g., Decoder.PeekKind, Decoder.ReadToken, Decoder.ReadValue, or Decoder.SkipValue). Token.Clone copies the text to a token which stays valid.

  • As a Go value, as the constructors (e.g., String, Int, Uint, Float) make it. Such a token is valid forever.

func Bool

func Bool(b bool) Token

Bool constructs a Token of a JSON boolean.

func Float

func Float(n float64) Token

Float constructs a Token of a JSON number of a 64-bit floating-point number, formatted as ECMA-262, 10th edition, section 7.1.12.1 and RFC 8785, section 3.2.2.3 do, except that -0 is formatted as -0. NaN, +Inf and -Inf are JSON strings of the values "NaN", "Infinity" and "-Infinity".

func Float32

func Float32(n float32) Token

Float32 constructs a Token of a JSON number of a 32-bit floating-point number, formatted as ECMA-262, 10th edition, section 7.1.12.1 does, except that -0 is formatted as -0. NaN, +Inf and -Inf are JSON strings of the values "NaN", "Infinity" and "-Infinity".

Most JSON libraries and standards take JSON numbers as 64-bit floating-point numbers: use 32-bit precision only if the decoder knows that the number has only 32-bit precision. In any other case, use Float.

func Int

func Int(n int64) Token

Int constructs a Token of a JSON number of an int64.

func String

func String(s string) Token

String constructs a Token of a JSON string. The string should be valid UTF-8: invalid bytes may be mangled as the Unicode replacement character.

func Uint

func Uint(n uint64) Token

Uint constructs a Token of a JSON number of a uint64.

func (Token) Bool

func (t Token) Bool() bool

Bool returns the value of a JSON boolean. It panics if the token is not a JSON boolean.

func (Token) Clone

func (t Token) Clone() Token

Clone returns a copy of the token whose value is not in the buffer of a Decoder: it stays valid after the following calls of the Decoder. A token which a constructor made is returned as it is.

func (Token) Float

func (t Token) Float() (float64, error)

Float returns the floating-point value of a JSON number, parsed with 64 bits of precision.

If the number is out of the range of a float64, it returns +Inf or -Inf with an error which matches strconv.ErrRange.

It returns NaN, +Inf or -Inf for a JSON string of the value "NaN", "Infinity" or "-Infinity".

It panics if the token is not a JSON number or one of those JSON strings.

func (Token) Float32

func (t Token) Float32() (float32, error)

Float32 returns the floating-point value of a JSON number, parsed with 32 bits of precision.

If the number is out of the range of a float32, it returns +Inf or -Inf with an error which matches strconv.ErrRange.

It returns NaN, +Inf or -Inf for a JSON string of the value "NaN", "Infinity" or "-Infinity".

It panics if the token is not a JSON number or one of those JSON strings.

Most JSON libraries and standards take JSON numbers as 64-bit floating-point numbers: use this method only if the number is known to have only 32 bits of precision (as Float32 writes it). In any other case, use Token.Float.

func (Token) Int

func (t Token) Int() (int64, error)

Int returns the signed integer value of a JSON number.

It reports an error which matches strconv.ErrSyntax if the number is not in the restricted grammar of a signed integer, and one which matches strconv.ErrRange if it is a signed integer out of the range of an int64. It returns a reasonable value even with an error: the fraction is truncated toward zero, and a number out of the range is saturated at the closest end.

It panics if the token is not a JSON number.

func (Token) Kind

func (t Token) Kind() Kind

Kind returns the kind of the token. It panics for a raw token which the decoder has moved past.

func (Token) String

func (t Token) String() string

String returns the unescaped value of a JSON string. For a token of another kind, it returns its raw JSON text.

func (Token) Uint

func (t Token) Uint() (uint64, error)

Uint returns the unsigned integer value of a JSON number.

It reports an error which matches strconv.ErrSyntax if the number is not in the restricted grammar of an unsigned integer, and one which matches strconv.ErrRange if it is an unsigned integer out of the range of a uint64. It returns a reasonable value even with an error: the fraction is truncated toward zero, and a number out of the range is saturated at the closest end.

It panics if the token is not a JSON number.

type Value

type Value []byte //nolint:recvcheck // the methods of encoding/json/jsontext.Value

Value is a raw JSON value, one of:

  • a JSON literal (i.e., null, true, or false)
  • a JSON string (e.g., "hello, world!")
  • a JSON number (e.g., 123.456)
  • a whole JSON object (e.g., {"fizz":"buzz"} )
  • a whole JSON array (e.g., [1,2,3] )

A Value can hold a whole object or array, which a Token can't. A Value may have leading and trailing white space.

func (*Value) Canonicalize

func (v *Value) Canonicalize(opts ...Options) error

Canonicalize formats v in the canonical form of the JSON Canonicalization Scheme (JCS) of RFC 8785: a value of the same meaning, which Canonicalize doesn't change.

The strings are in their minimal form, the numbers are formatted as double precision numbers, the members of the objects are sorted by their names, and the white space is removed.

It is Value.Format with the options CanonicalizeRawInts(true), CanonicalizeRawFloats(true), ReorderRawObjects(true), Multiline(false), SpaceAfterColon(false) and SpaceAfterComma(false), and an empty indentation, followed by the options given.

JCS takes all JSON numbers as IEEE 754 double precision numbers: a number which needs more precision loses it. For example, integers beyond ±2⁵³ lose their precision. To keep the representation of the integers, set CanonicalizeRawInts to false:

v.Canonicalize(jsontext.CanonicalizeRawInts(false))

func (Value) Clone

func (v Value) Clone() Value

Clone returns a copy of v.

func (*Value) Compact

func (v *Value) Compact(opts ...Options) error

Compact removes the white space of v.

It doesn't change the representation of the strings and numbers. So that it formats as many values as it can, it takes values of duplicate names and invalid UTF-8.

It is Value.Format with the options AllowDuplicateNames(true), AllowInvalidUTF8(true), PreserveRawStrings(true), Multiline(false), SpaceAfterColon(false) and SpaceAfterComma(false), and an empty indentation, followed by the options given.

func (*Value) Format

func (v *Value) Format(opts ...Options) error

Format formats v in place.

Without options, it validates v as RFC 7493 specifies, and writes it in its minimal form: without white space, and the strings in their shortest encoding.

The options which matter are AllowDuplicateNames, AllowInvalidUTF8, EscapeForHTML, EscapeForJS, PreserveRawStrings, CanonicalizeRawInts, CanonicalizeRawFloats, ReorderRawObjects, SpaceAfterColon, SpaceAfterComma, Multiline, WithIndent and WithIndentPrefix; the others are ignored.

It succeeds if v is valid under the same options. If v is formatted already, it is not changed.

func (*Value) Indent

func (v *Value) Indent(opts ...Options) error

Indent formats the white space of v so that each element of an object or array starts a line which is indented by its depth.

It doesn't change the representation of the strings and numbers. So that it formats as many values as it can, it takes values of duplicate names and invalid UTF-8.

It is Value.Format with the options AllowDuplicateNames(true), AllowInvalidUTF8(true), PreserveRawStrings(true), Multiline(true), SpaceAfterColon(true) and WithIndent("\t"), followed by the options given.

func (Value) IsValid

func (v Value) IsValid(opts ...Options) bool

IsValid reports whether v is valid JSON under the options.

Without options, it validates v as RFC 7493 specifies: v is valid UTF-8, the escape sequences of the strings are of valid Unicode code points, and the names of each object are unique. It doesn't check whether the numbers fit in any numeric type (e.g., float64, int64 or uint64).

The options which matter are AllowDuplicateNames and AllowInvalidUTF8; the others are ignored.

func (Value) Kind

func (v Value) Kind() Kind

Kind returns the kind of the first token of v. A valid value never starts with KindEndObject or KindEndArray.

func (Value) MarshalJSON

func (v Value) MarshalJSON() ([]byte, error)

MarshalJSON returns v as its JSON encoding, without validating it. It returns null for a nil v.

func (Value) String

func (v Value) String() string

String returns the text of v, or null for a nil v.

func (*Value) UnmarshalJSON

func (v *Value) UnmarshalJSON(b []byte) error

UnmarshalJSON sets v to a copy of b, without validating it.

Jump to

Keyboard shortcuts

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