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 ¶
- Variables
- func AppendFloat(dst []byte, src float64, bits int) []byte
- func AppendFormat[Bytes ~[]byte | ~string](dst []byte, src Bytes, opts ...Options) ([]byte, error)
- func AppendQuote[Bytes ~[]byte | ~string](dst []byte, src Bytes) ([]byte, error)
- func AppendUnquote[Bytes ~[]byte | ~string](dst []byte, src Bytes) ([]byte, error)
- type Decoder
- func (d *Decoder) InputOffset() int64
- func (d *Decoder) Options() Options
- func (d *Decoder) PeekKind() Kind
- func (d *Decoder) ReadToken() (Token, error)
- func (d *Decoder) ReadValue() (Value, error)
- func (d *Decoder) Reset(r io.Reader, opts ...Options)
- func (d *Decoder) SkipValue() error
- func (d *Decoder) StackDepth() int
- func (d *Decoder) StackIndex(i int) (Kind, int64)
- func (d *Decoder) StackPointer() Pointer
- func (d *Decoder) UnreadBuffer() []byte
- type Encoder
- func (e *Encoder) AvailableBuffer() []byte
- func (e *Encoder) Options() Options
- func (e *Encoder) OutputOffset() int64
- func (e *Encoder) Reset(w io.Writer, opts ...Options)
- func (e *Encoder) StackDepth() int
- func (e *Encoder) StackIndex(i int) (Kind, int64)
- func (e *Encoder) StackPointer() Pointer
- func (e *Encoder) WriteToken(t Token) error
- func (e *Encoder) WriteValue(v Value) error
- type Kind
- type Options
- func AllowDuplicateNames(v bool) Options
- func AllowInvalidUTF8(v bool) Options
- func CanonicalizeRawFloats(v bool) Options
- func CanonicalizeRawInts(v bool) Options
- func EscapeForHTML(v bool) Options
- func EscapeForJS(v bool) Options
- func Multiline(v bool) Options
- func PreserveRawStrings(v bool) Options
- func ReorderRawObjects(v bool) Options
- func SpaceAfterColon(v bool) Options
- func SpaceAfterComma(v bool) Options
- func WithIndent(indent string) Options
- func WithIndentPrefix(prefix string) Options
- type Pointer
- type SyntacticError
- type Token
- type Value
- func (v *Value) Canonicalize(opts ...Options) error
- func (v Value) Clone() Value
- func (v *Value) Compact(opts ...Options) error
- func (v *Value) Format(opts ...Options) error
- func (v *Value) Indent(opts ...Options) error
- func (v Value) IsValid(opts ...Options) bool
- func (v Value) Kind() Kind
- func (v Value) MarshalJSON() ([]byte, error)
- func (v Value) String() string
- func (v *Value) UnmarshalJSON(b []byte) error
Constants ¶
This section is empty.
Variables ¶
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 */} )
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Options returns the options of the decoder: the ones it was constructed or last reset with, which follow a later Reset.
func (*Decoder) PeekKind ¶
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 ¶
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 ¶
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) SkipValue ¶
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 ¶
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 ¶
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 ¶
StackPointer returns a JSON Pointer (RFC 6901) to the last value which was read.
func (*Decoder) UnreadBuffer ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) StackDepth ¶
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 ¶
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 ¶
StackPointer returns a JSON Pointer (RFC 6901) to the last value which was written.
func (*Encoder) WriteToken ¶
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 ¶
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 )
type 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
SpaceAfterColon specifies that a space is written after the colon which follows a JSON object name.
This affects encoding only.
func SpaceAfterComma ¶
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 ¶
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 ¶
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 ¶
AppendToken appends the token tok to p and returns the pointer.
func (Pointer) Contains ¶
Contains reports whether the JSON value which p points to is the one which pc points to or contains it.
func (Pointer) IsValid ¶
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 ¶
LastToken returns the last token of p. The last token of the empty pointer is the empty string.
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 Float ¶
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 ¶
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 String ¶
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 (Token) Bool ¶
Bool returns the value of a JSON boolean. It panics if the token is not a JSON boolean.
func (Token) Clone ¶
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 ¶
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 ¶
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 ¶
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 ¶
Kind returns the kind of the token. It panics for a raw token which the decoder has moved past.
func (Token) 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 ¶
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 ¶
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) Compact ¶
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 ¶
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 ¶
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 ¶
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 ¶
Kind returns the kind of the first token of v. A valid value never starts with KindEndObject or KindEndArray.
func (Value) MarshalJSON ¶
MarshalJSON returns v as its JSON encoding, without validating it. It returns null for a nil v.
func (*Value) UnmarshalJSON ¶
UnmarshalJSON sets v to a copy of b, without validating it.