Documentation
¶
Overview ¶
Package json encodes, decodes, formats, and edits JSON while preserving the source document's syntax tree, whitespace, and comments.
Decoding returns a *Meta alongside the decoded Go value. Meta and the Node values derived from it are live handles into the parsed document. Mutating a Node mutates its owning Meta. Node values are not detached snapshots; use MarshalMeta or EncodeMeta to observe the current document bytes.
Unless a function states otherwise, pointer parameters must be non-nil and Node or Comment receivers must have been obtained from this package. A zero Node or Comment is not a valid receiver.
Index ¶
- Variables
- func Compact(dst *bytes.Buffer, src []byte) error
- func CompactWithOptions(dst *bytes.Buffer, src []byte, opts SyntaxOptions) error
- func HTMLEscape(dst *bytes.Buffer, src []byte)
- func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error
- func IndentWithOptions(dst *bytes.Buffer, src []byte, prefix, indent string, opts SyntaxOptions) error
- func Marshal(v any) ([]byte, error)
- func MarshalMeta(m *Meta) ([]byte, error)
- func Valid(data []byte) bool
- func ValidWithOptions(data []byte, opts SyntaxOptions) bool
- type AppendSegment
- type Comment
- type CommentError
- type CommentSet
- type Comments
- type Decoder
- type Encoder
- type InvalidUnmarshalError
- type Marshaler
- type MarshalerError
- type Meta
- type Node
- func (n Node) ArrayElement(index int) (Node, bool)
- func (n Node) ArrayValue(index int) (Node, bool)
- func (n Node) At(path ...any) (Node, error)
- func (n Node) Bytes() []byte
- func (n Node) Children() []Node
- func (n Node) Clone() Node
- func (n Node) Comments() CommentSet
- func (n Node) Decode(v any) error
- func (n Node) InsertArrayValue(index int, value any) error
- func (n Node) InsertAt(value any, path ...any) error
- func (n Node) InsertJSONPointer(pointer string, value any) error
- func (n Node) InsertObjectField(name string, value any) error
- func (n Node) JSONPointer(pointer string) (Node, error)
- func (n Node) Key() (Node, bool)
- func (target Node) Merge(patch Node) error
- func (n Node) ObjectField(name string) (Node, bool)
- func (n Node) ObjectFieldNode(name string) (Node, bool)
- func (n Node) ObjectFields() iter.Seq2[string, Node]
- func (target Node) Patch(patches ...Patch) error
- func (n Node) RemoveArrayValue(index int) error
- func (n Node) RemoveAt(path ...any) error
- func (n Node) RemoveJSONPointer(pointer string) error
- func (n Node) RemoveObjectField(name string) error
- func (n Node) RenameObjectField(oldName, newName string) error
- func (n Node) Replace(v any) error
- func (n Node) ReplaceArrayValue(index int, value any) error
- func (n Node) ReplaceAt(value any, path ...any) error
- func (n Node) ReplaceJSONPointer(pointer string, value any) error
- func (n Node) ReplaceObjectField(name string, value any) error
- func (n Node) TrailingComment() (Comment, bool)
- func (n Node) Type() NodeType
- func (n Node) Value() (Node, bool)
- type NodeType
- type Number
- type ParseError
- type Patch
- type PathError
- type RawMessage
- type SyntaxError
- type SyntaxOptions
- type TokenType
- type UnmarshalTypeError
- type Unmarshaler
- type UnsupportedTypeError
- type UnsupportedValueError
Constants ¶
This section is empty.
Variables ¶
var ( // ErrUnexpectedEOF reports input that ended before a complete value was parsed. ErrUnexpectedEOF = errors.New("unexpected EOF") // ErrUnexpectedToken reports a token that is not valid at the current parse position. ErrUnexpectedToken = errors.New("unexpected token") // ErrInvalidString reports a malformed string literal. ErrInvalidString = errors.New("invalid string") // ErrInvalidNumber reports a malformed number literal. ErrInvalidNumber = errors.New("invalid number") // ErrInvalidSpace reports whitespace that is not valid for the active syntax options. ErrInvalidSpace = errors.New("invalid whitespace") // ErrDuplicateObjectKey reports an object key repeated in the same object. ErrDuplicateObjectKey = errors.New("duplicate object key") )
var ( // ErrWrongNodeType reports an operation applied to the wrong JSON node type. ErrWrongNodeType = errors.New("wrong node type") // ErrObjectFieldNotFound reports a missing object field. ErrObjectFieldNotFound = errors.New("object field not found") // ErrObjectFieldExists reports an object insertion for a field that already exists. ErrObjectFieldExists = errors.New("object field exists") // ErrArrayIndexOutOfRange reports an array index outside the supported range. ErrArrayIndexOutOfRange = errors.New("array index out of range") )
var ( // ErrInvalidPatch reports a patch document that is not a valid patch array. ErrInvalidPatch = errors.New("invalid JSON patch") // ErrInvalidPatchOperation reports an invalid operation inside a patch document. ErrInvalidPatchOperation = errors.New("invalid JSON patch operation") // ErrPatchTestFailed reports a failed JSON Patch test operation. ErrPatchTestFailed = errors.New("JSON patch test failed") )
var ( // ErrEmptyPath reports a mutation operation that requires at least one path segment. ErrEmptyPath = errors.New("empty path") // ErrInvalidPathSegment reports a path segment with an unsupported type or value. ErrInvalidPathSegment = errors.New("invalid path segment") // ErrInvalidJSONPointer reports a malformed RFC 6901 JSON Pointer. ErrInvalidJSONPointer = errors.New("invalid JSON pointer") // ErrInvalidAppend reports use of the append marker outside array insertion. ErrInvalidAppend = errors.New("invalid append segment") )
var ErrInvalidComment = errors.New("invalid comment")
ErrInvalidComment reports replacement text that cannot fit the existing comment form.
Functions ¶
func Compact ¶
Compact appends src to dst with insignificant whitespace removed.
dst must be non-nil. Compact accepts strict JSON.
func CompactWithOptions ¶
func CompactWithOptions(dst *bytes.Buffer, src []byte, opts SyntaxOptions) error
CompactWithOptions appends src to dst with insignificant whitespace removed.
dst must be non-nil. CompactWithOptions accepts syntax enabled by opts and preserves comments.
func HTMLEscape ¶
HTMLEscape appends src to dst with HTML-significant characters escaped inside JSON strings.
dst must be non-nil.
func Indent ¶
Indent appends an indented form of src to dst.
dst must be non-nil. Indent accepts strict JSON.
func IndentWithOptions ¶
func IndentWithOptions(dst *bytes.Buffer, src []byte, prefix, indent string, opts SyntaxOptions) error
IndentWithOptions appends an indented form of src to dst.
dst must be non-nil. IndentWithOptions accepts syntax enabled by opts and preserves comments.
func ValidWithOptions ¶
func ValidWithOptions(data []byte, opts SyntaxOptions) bool
ValidWithOptions reports whether data is a complete JSON value for opts.
Types ¶
type AppendSegment ¶
type AppendSegment struct{}
AppendSegment marks an array append operation in InsertAt paths.
var Append AppendSegment
Append appends to an array when used as the final segment of InsertAt.
type Comment ¶
type Comment struct {
// contains filtered or unexported fields
}
Comment is a live handle to one source comment token.
Copying a Comment copies the handle. Mutating a Comment updates its owning Meta. A zero Comment is not a valid receiver.
func (Comment) ReplaceText ¶
ReplaceText replaces the comment text while preserving the existing comment form.
type CommentError ¶
CommentError describes an invalid comment replacement.
func (CommentError) Error ¶
func (e CommentError) Error() string
Error returns the formatted comment error.
func (CommentError) Unwrap ¶
func (e CommentError) Unwrap() error
Unwrap returns the underlying comment error.
type CommentSet ¶
CommentSet groups comments by their relationship to a node.
func (CommentSet) First ¶
func (cs CommentSet) First() (Comment, bool)
First returns the first leading, dangling, or trailing comment in that order.
func (CommentSet) Text ¶
func (cs CommentSet) Text() string
Text joins all comments in leading, dangling, then trailing order.
type Comments ¶
type Comments []Comment
Comments is an ordered group of comment handles.
type Decoder ¶
type Decoder struct {
SyntaxOptions
// contains filtered or unexported fields
}
Decoder reads JSON values from an input stream.
A Decoder is stateful and not safe for concurrent use. Its methods require a non-nil *Decoder returned by NewDecoder, NewJSONCDecoder, or NewJSON5Decoder.
func NewDecoder ¶
NewDecoder returns a decoder that reads strict JSON from r.
r must be non-nil and must remain usable for the lifetime of the Decoder.
func NewJSON5Decoder ¶
NewJSON5Decoder returns a decoder that reads JSON5 from r.
r must be non-nil and must remain usable for the lifetime of the Decoder.
func NewJSONCDecoder ¶
NewJSONCDecoder returns a decoder that reads JSONC from r.
r must be non-nil and must remain usable for the lifetime of the Decoder.
func (*Decoder) Buffered ¶
Buffered returns a reader for bytes already read from the underlying reader but not consumed by the decoder.
func (*Decoder) Decode ¶
Decode reads the next JSON value, stores it in v, and returns its metadata tree.
v must be a non-nil pointer. At the end of a stream, Decode returns io.EOF.
func (*Decoder) DecodeMeta ¶
DecodeMeta reads one complete JSON value and returns its metadata tree.
func (*Decoder) DisallowUnknownFields ¶
func (d *Decoder) DisallowUnknownFields()
DisallowUnknownFields causes Decode to reject object keys that do not match a destination struct field.
func (*Decoder) InputOffset ¶
InputOffset returns the byte offset of the decoder's current input position.
type Encoder ¶
type Encoder struct {
Indent string
Prefix string
SyntaxOptions
// contains filtered or unexported fields
}
Encoder writes JSON values to an output stream.
An Encoder is stateful and not safe for concurrent use. Its methods require a non-nil *Encoder returned by NewEncoder or NewJSON5Encoder.
func NewEncoder ¶
NewEncoder returns an encoder that writes strict JSON to w.
w must be non-nil and must remain usable for the lifetime of the Encoder.
func NewJSON5Encoder ¶
NewJSON5Encoder returns an encoder that writes JSON5-compatible output to w.
w must be non-nil and must remain usable for the lifetime of the Encoder.
func (*Encoder) EncodeMeta ¶
EncodeMeta writes the current bytes represented by m.
m must be non-nil.
func (*Encoder) SetEscapeHTML ¶
SetEscapeHTML controls whether string values escape HTML-significant characters.
type InvalidUnmarshalError ¶
InvalidUnmarshalError describes an invalid target passed to Unmarshal, Decoder.Decode, or Node.Decode.
Those APIs require v to be a non-nil pointer to the value being populated.
func (InvalidUnmarshalError) Error ¶
func (e InvalidUnmarshalError) Error() string
Error returns the formatted invalid unmarshal target error.
type Marshaler ¶
Marshaler is implemented by values that encode their own JSON representation.
MarshalJSON must return one complete JSON value. Pointer receiver implementations are called only when the source value is addressable.
type MarshalerError ¶
MarshalerError wraps an error returned by a Marshaler implementation.
func (*MarshalerError) Error ¶
func (e *MarshalerError) Error() string
Error returns the formatted marshaler error.
func (*MarshalerError) Unwrap ¶
func (e *MarshalerError) Unwrap() error
Unwrap returns the error reported by the Marshaler.
type Meta ¶
type Meta struct {
SST sst.SST[TokenType, NodeType]
Indent string
// contains filtered or unexported fields
}
Meta owns a parsed JSON document and its preserved syntax metadata.
Meta values are mutable and not safe for concurrent use. Methods on *Meta require a non-nil pointer returned by this package.
func Unmarshal ¶
Unmarshal parses one JSON value from data, stores it in v, and returns the parsed metadata tree.
v must be a non-nil pointer. The returned *Meta owns the parsed document; Nodes obtained from it remain live handles into that Meta.
func (*Meta) Clone ¶
Clone returns a detached copy of m.
The returned Meta preserves m's syntax options, indentation, tokens, comments, and tree shape. Mutating either Meta does not affect the other.
func (*Meta) Comments ¶
func (m *Meta) Comments() CommentSet
Comments returns comments adjacent to the document root.
m must be non-nil. Returned Comment values are live handles into m.
func (*Meta) Leaves ¶
Leaves iterates over leaf nodes in source order.
m must be non-nil. Yielded Node values are live handles into m.
func (*Meta) Merge ¶
Merge applies an RFC 7396 JSON Merge Patch to m.
m and patch must be non-nil. The patch document is read but not mutated.
func (*Meta) Nodes ¶
Nodes iterates over every node in source order.
m must be non-nil. Yielded Node values are live handles into m.
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node is a live handle to one node in a Meta syntax tree.
Copying a Node copies the handle, not the underlying syntax tree. Mutating methods update the owning Meta. A zero Node is not a valid receiver.
func (Node) ArrayElement ¶
ArrayElement returns the array-element wrapper node at index.
The returned Node is a live handle into the same Meta.
func (Node) ArrayValue ¶
ArrayValue returns the value at index in an array.
The returned Node is a live handle into the same Meta.
func (Node) At ¶
At follows path from this node and returns the addressed node.
String segments select object fields, int segments select array indexes, and Append is invalid for access. The returned Node is a live handle into the same Meta.
func (Node) Children ¶
Children returns handles for this node's direct children.
The returned slice is a snapshot of child handles. Each Node in it remains a live handle into the same Meta.
func (Node) Clone ¶
Clone returns a detached copy of this node.
The returned Node is a live handle into a new Meta. Mutating either node does not affect the other.
func (Node) Comments ¶
func (n Node) Comments() CommentSet
Comments returns comments adjacent to this node.
Returned Comment values are live handles into the same Meta.
func (Node) InsertArrayValue ¶
InsertArrayValue inserts value before index in an array.
index may equal the current array length to append. If value is a Node or *Meta, its current JSON value is cloned into this node's owning Meta.
func (Node) InsertAt ¶
InsertAt inserts value at path.
The final path segment may be Append to append to an array. If value is a Node or *Meta, its current JSON value is cloned into this node's owning Meta.
func (Node) InsertJSONPointer ¶
InsertJSONPointer inserts value at an RFC 6901 JSON Pointer.
A final "-" token appends to an array. If value is a Node or *Meta, its current JSON value is cloned into this node's owning Meta.
func (Node) InsertObjectField ¶
InsertObjectField appends a new object field.
If value is a Node or *Meta, its current JSON value is cloned into this node's owning Meta.
func (Node) JSONPointer ¶
JSONPointer follows an RFC 6901 JSON Pointer from this node.
The returned Node is a live handle into the same Meta.
func (Node) Merge ¶
Merge applies an RFC 7396 JSON Merge Patch to target.
target and patch must be valid Nodes. The patch value is read from its owning Meta and cloned into target's owning Meta as needed.
func (Node) ObjectField ¶
ObjectField returns the value for object field name.
The returned Node is a live handle into the same Meta.
func (Node) ObjectFieldNode ¶
ObjectFieldNode returns the object-field wrapper node for name.
The returned Node is a live handle into the same Meta.
func (Node) ObjectFields ¶
ObjectFields iterates over this object's fields in source order.
Yielded Nodes are object-field wrapper nodes and are live handles into the same Meta. Non-object receivers yield nothing.
func (Node) Patch ¶
Patch applies RFC 6902 JSON Patch operations to target atomically.
If an operation fails, target is unchanged.
func (Node) RemoveArrayValue ¶
RemoveArrayValue removes the array value at index.
func (Node) RemoveJSONPointer ¶
RemoveJSONPointer removes the node addressed by an RFC 6901 JSON Pointer.
func (Node) RemoveObjectField ¶
RemoveObjectField removes an existing object field.
func (Node) RenameObjectField ¶
RenameObjectField changes an existing object field's key.
func (Node) Replace ¶
Replace replaces this node with v.
If v is a Node or *Meta, its current JSON value is cloned into this node's owning Meta; later mutations to v's original owner do not affect this node.
func (Node) ReplaceArrayValue ¶
ReplaceArrayValue replaces the array value at index.
func (Node) ReplaceAt ¶
ReplaceAt replaces the node addressed by path.
An empty path replaces the receiver. If value is a Node or *Meta, its current JSON value is cloned into this node's owning Meta.
func (Node) ReplaceJSONPointer ¶
ReplaceJSONPointer replaces the node addressed by an RFC 6901 JSON Pointer.
An empty pointer replaces the receiver. If value is a Node or *Meta, its current JSON value is cloned into this node's owning Meta.
func (Node) ReplaceObjectField ¶
ReplaceObjectField replaces the value for an existing object field.
func (Node) TrailingComment ¶
TrailingComment returns the first trailing comment adjacent to this node.
The returned Comment is a live handle into the same Meta.
type NodeType ¶
type NodeType int8
NodeType identifies a node in the parsed JSON syntax tree.
const ( // NodeTypeIllegal identifies an invalid node. NodeTypeIllegal NodeType = iota // NodeTypeObject identifies a JSON object. NodeTypeObject // NodeTypeObjectField identifies an object field wrapper node. NodeTypeObjectField // NodeTypeArray identifies a JSON array. NodeTypeArray // NodeTypeArrayElement identifies an array element wrapper node. NodeTypeArrayElement // NodeTypeString identifies a string value. NodeTypeString // NodeTypeNumber identifies a number value. NodeTypeNumber // NodeTypeBool identifies a boolean value. NodeTypeBool // NodeTypeNull identifies null. NodeTypeNull )
type Number ¶
type Number string
Number stores a JSON number literal without converting it to float64.
func (Number) MarshalJSON ¶
MarshalJSON returns n as one JSON number.
type ParseError ¶
type ParseError struct {
Err error
Token token
}
ParseError describes a lexer or parser error at a concrete input token.
func (ParseError) Error ¶
func (e ParseError) Error() string
Error returns the formatted parse error.
func (ParseError) Unwrap ¶
func (e ParseError) Unwrap() error
Unwrap returns the underlying parse error sentinel.
type Patch ¶
Patch is one RFC 6902 JSON Patch operation.
Value may be a plain Go value, Node, or *Meta. When Value is a Node or *Meta, the operation clones its current JSON value before inserting it into the target.
type PathError ¶
PathError describes an error while applying a path or JSON Pointer operation.
type RawMessage ¶
type RawMessage []byte
RawMessage is a raw encoded JSON value.
MarshalJSON emits nil RawMessage values as null. UnmarshalJSON requires a non-nil *RawMessage receiver and replaces the receiver's bytes with a copy of data.
func (RawMessage) MarshalJSON ¶
func (m RawMessage) MarshalJSON() ([]byte, error)
MarshalJSON returns m as one encoded JSON value.
func (*RawMessage) UnmarshalJSON ¶
func (m *RawMessage) UnmarshalJSON(data []byte) error
UnmarshalJSON replaces m with a copy of data.
m must be non-nil.
type SyntaxError ¶
type SyntaxError struct {
Offset int64
// contains filtered or unexported fields
}
SyntaxError describes invalid JSON syntax.
func (*SyntaxError) Error ¶
func (e *SyntaxError) Error() string
Error returns the formatted syntax error.
type SyntaxOptions ¶
type SyntaxOptions struct {
// ECMAScriptIdentifiers allows unquoted object keys that are valid
// ECMAScript identifiers.
ECMAScriptIdentifiers bool
// TrailingCommas allows a comma after the final array element or object field.
TrailingCommas bool
// SingleQuotedStrings allows strings quoted with single quotes.
SingleQuotedStrings bool
// MultilineStrings allows line continuations inside string literals.
MultilineStrings bool
// StringCharacterEscapes allows JSON5 character escapes that strict JSON
// does not permit.
StringCharacterEscapes bool
// HexadecimalNumbers allows hexadecimal number literals.
HexadecimalNumbers bool
// LeadingOrTrailingDecimalPoints allows number literals such as .1 and 1.
LeadingOrTrailingDecimalPoints bool
// LeadingPlusSigns allows a leading plus sign on number literals.
LeadingPlusSigns bool
// IEEE754Numbers allows Infinity, -Infinity, and NaN number literals.
IEEE754Numbers bool
// SingleLineComments allows // comments.
SingleLineComments bool
// MultilineComments allows block comments.
MultilineComments bool
// AdditionalWhitespace allows JSON5 whitespace beyond strict JSON's space,
// tab, carriage return, and line feed.
AdditionalWhitespace bool
}
SyntaxOptions controls optional JSON syntax extensions accepted by the decoder and, where applicable, emitted by the encoder.
func JSON5SyntaxOptions ¶
func JSON5SyntaxOptions() SyntaxOptions
JSON5SyntaxOptions returns the full set of JSON5 syntax extensions.
func JSONCSyntaxOptions ¶
func JSONCSyntaxOptions() SyntaxOptions
JSONCSyntaxOptions returns the syntax extensions commonly used by JSONC.
type TokenType ¶
type TokenType int8
TokenType identifies a lexical token in preserved source text.
const ( // TokenAnchor is an internal zero-width marker used to delimit nodes. TokenAnchor TokenType = -1 // TokenIllegal identifies an invalid token. TokenIllegal TokenType = iota // TokenEOF identifies the end of input. TokenEOF // TokenIdentifier identifies JSON identifiers such as true, false, null, or JSON5 names. TokenIdentifier // TokenNumber identifies a number literal. TokenNumber // TokenString identifies a string literal. TokenString // TokenColon identifies a colon. TokenColon // TokenComma identifies a comma. TokenComma // TokenDelim identifies a brace or bracket delimiter. TokenDelim // TokenWhitespace identifies horizontal whitespace. TokenWhitespace // TokenNewline identifies a newline. TokenNewline // TokenComment identifies a line or block comment. TokenComment )
type UnmarshalTypeError ¶
type UnmarshalTypeError struct {
Value string
Type reflect.Type
Offset int64
Struct string
Field string
}
UnmarshalTypeError describes a JSON value that cannot be assigned to the requested Go type.
func (*UnmarshalTypeError) Error ¶
func (e *UnmarshalTypeError) Error() string
Error returns the formatted unmarshal type error.
type Unmarshaler ¶
Unmarshaler is implemented by values that decode their own JSON representation.
UnmarshalJSON receives the exact bytes for the value being decoded. Pointer receiver implementations are called only when the target value is addressable.
type UnsupportedTypeError ¶
UnsupportedTypeError describes a Go type that cannot be encoded as JSON.
func (*UnsupportedTypeError) Error ¶
func (e *UnsupportedTypeError) Error() string
Error returns the formatted unsupported type error.
type UnsupportedValueError ¶
UnsupportedValueError describes a Go value that cannot be encoded as JSON.
func (*UnsupportedValueError) Error ¶
func (e *UnsupportedValueError) Error() string
Error returns the formatted unsupported value error.