Movatterモバイル変換


[0]ホーム

URL:


jsontext

package
v0.0.0-...-4849db3Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2025 License:BSD-3-ClauseImports:15Imported by:173

Details

Repository

github.com/go-json-experiment/json

Links

Documentation

Overview

Package jsontext implements syntactic processing of JSONas specified inRFC 4627,RFC 7159,RFC 7493,RFC 8259, andRFC 8785.JSON is a simple data interchange format that can representprimitive data types such as booleans, strings, and numbers,in addition to structured data types such as objects and arrays.

TheEncoder andDecoder types are used to encode or decodea stream of JSON tokens or values.

Tokens and Values

A JSON token refers to the basic structural elements 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 for a JSON object (i.e., '{' or '}')
  • a begin or end delimiter for a JSON array (i.e., '[' or ']')

A JSON token is represented by theToken type in Go. Technically,there are two additional structural characters (i.e., ':' and ','),but there is noToken representation for them since their presencecan be inferred by the structure of the JSON grammar itself.For example, there must always be an implicit colon betweenthe name and value of a JSON object member.

A JSON value refers to a complete unit of JSON data:

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

A JSON value is represented by theValue type in Go and is a []bytecontaining the raw textual representation of the value. There is some overlapbetween tokens and values as both contain literals, strings, and numbers.However, only a value can represent the entirety of a JSON object or array.

TheEncoder andDecoder types contain methods to read or write the nextToken orValue in a sequence. They maintain a state machine to validatewhether the sequence of JSON tokens and/or values produces a valid JSON.Options may be passed to theNewEncoder orNewDecoder constructorsto configure the syntactic behavior of encoding and decoding.

Terminology

The terms "encode" and "decode" are used for syntactic functionalitythat is concerned with processing JSON based on its grammar, andthe terms "marshal" and "unmarshal" are used for semantic functionalitythat determines the meaning of JSON values as Go values and vice-versa.This package (i.e.,jsontext) deals with JSON at a syntactic layer,whileencoding/json/v2 deals with JSON at a semantic layer.The goal is to provide a clear distinction between functionality thatis purely concerned with encoding versus that of marshaling.For example, one can directly encode a stream of JSON tokens withoutneeding to marshal a concrete Go value representing them.Similarly, one can decode a stream of JSON tokens withoutneeding to unmarshal them into a concrete Go value.

This package uses JSON terminology when discussing JSON, which may differfrom related concepts in Go or elsewhere in computing literature.

  • a JSON "object" refers to an unordered collection of name/value members.
  • a JSON "array" refers to an ordered sequence of elements.
  • a JSON "value" refers to either a literal (i.e., null, false, or true),string, number, object, or array.

SeeRFC 8259 for more information.

Specifications

Relevant specifications includeRFC 4627,RFC 7159,RFC 7493,RFC 8259,andRFC 8785. Each RFC is generally a stricter subset of another RFC.In increasing order of strictness:

  • RFC 4627 andRFC 7159 do not require (but recommend) the use of UTF-8and also do not require (but recommend) that object names be unique.
  • RFC 8259 requires the use of UTF-8,but does not require (but recommends) that object names be unique.
  • RFC 7493 requires the use of UTF-8and also requires that object names be unique.
  • RFC 8785 defines a canonical representation. It requires the use of UTF-8and also requires that object names be unique and in a specific ordering.It specifies exactly how strings and numbers must be formatted.

The primary difference betweenRFC 4627 andRFC 7159 is that the formerrestricted top-level values to only JSON objects and arrays, whileRFC 7159 and subsequent RFCs permit top-level values to additionally beJSON nulls, booleans, strings, or numbers.

By default, this package operates onRFC 7493, but can be configuredto operate according to the other RFC specifications.RFC 7493 is a stricter subset ofRFC 8259 and fully compliant with it.In particular, it makes specific choices about behavior thatRFC 8259leaves as undefined in order to ensure greater interoperability.

Security Considerations

See the "Security Considerations" section inencoding/json/v2.

Example (StringReplace)

This example demonstrates the use of theEncoder andDecoder toparse and modify JSON without unmarshaling it into a concrete Go type.

package mainimport ("bytes""fmt""io""log""strings""github.com/go-json-experiment/json/jsontext")func main() {// Example input with non-idiomatic use of "Golang" instead of "Go".const input = `{"title": "Golang version 1 is released","author": "Andrew Gerrand","date": "2012-03-28","text": "Today marks a major milestone in the development of the Golang programming language.","otherArticles": ["Twelve Years of Golang","The Laws of Reflection","Learn Golang from your browser"]}`// Using a Decoder and Encoder, we can parse through every token,// check and modify the token if necessary, and// write the token to the output.var replacements []jsontext.Pointerin := strings.NewReader(input)dec := jsontext.NewDecoder(in)out := new(bytes.Buffer)enc := jsontext.NewEncoder(out, jsontext.Multiline(true)) // expand for readabilityfor {// Read a token from the input.tok, err := dec.ReadToken()if err != nil {if err == io.EOF {break}log.Fatal(err)}// Check whether the token contains the string "Golang" and// replace each occurrence with "Go" instead.if tok.Kind() == '"' && strings.Contains(tok.String(), "Golang") {replacements = append(replacements, dec.StackPointer())tok = jsontext.String(strings.ReplaceAll(tok.String(), "Golang", "Go"))}// Write the (possibly modified) token to the output.if err := enc.WriteToken(tok); err != nil {log.Fatal(err)}}// Print the list of replacements and the adjusted JSON output.if len(replacements) > 0 {fmt.Println(`Replaced "Golang" with "Go" in:`)for _, where := range replacements {fmt.Println("\t" + where)}fmt.Println()}fmt.Println("Result:", out.String())}
Output:Replaced "Golang" with "Go" in:/title/text/otherArticles/0/otherArticles/2Result: {"title": "Go version 1 is released","author": "Andrew Gerrand","date": "2012-03-28","text": "Today marks a major milestone in the development of the Go programming language.","otherArticles": ["Twelve Years of Go","The Laws of Reflection","Learn Go from your browser"]}

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrDuplicateName =errors.New("duplicate object member name")

ErrDuplicateName indicates that a JSON token could not beencoded or decoded because it results in a duplicate JSON object name.This error is directly wrapped within aSyntacticError when produced.

The name of a duplicate JSON object member can be extracted as:

err := ...serr, ok := errors.AsType[*jsontext.SyntacticError](err)if ok && serr.Err == jsontext.ErrDuplicateName {ptr := serr.JSONPointer // JSON pointer to duplicate namename := ptr.LastToken() // duplicate name itself...}

This error is only returned ifAllowDuplicateNames is false.

View Source
var ErrNonStringName =errors.New("object member name must be a string")

ErrNonStringName indicates that a JSON token could not beencoded or decoded because it is not a string,as required for JSON object names according toRFC 8259, section 4.This error is directly wrapped within aSyntacticError when produced.

View Source
var Internal exporter

Internal is for internal use only.This is exempt from the Go compatibility agreement.

Functions

funcAppendFormat

func AppendFormat(dst, src []byte, opts ...Options) ([]byte,error)

AppendFormat formats the JSON value in src and appends it to dstaccording to the specified options.SeeValue.Format for more details about the formatting behavior.

The dst and src may overlap.If an error is reported, then the entirety of src is appended to dst.

funcAppendQuote

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

AppendQuote appends a double-quoted JSON string literal representing srcto dst and returns the extended buffer.It uses the minimal string representation perRFC 8785, section 3.2.2.2.Invalid UTF-8 bytes are replaced with the Unicode replacement characterand an error is returned at the end indicating the presence of invalid UTF-8.The dst must not overlap with the src.

funcAppendUnquote

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

AppendUnquote appends the decoded interpretation of src as adouble-quoted JSON string literal to dst and returns the extended buffer.The input src must be a JSON string without any surrounding whitespace.Invalid UTF-8 bytes are replaced with the Unicode replacement characterand an error is returned at the end indicating the presence of invalid UTF-8.Any trailing bytes after the JSON string literal results in an error.The dst must not overlap with the src.

Types

typeDecoder

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

Decoder is a streaming decoder for raw JSON tokens and values.It is used to read a stream of top-level JSON values,each separated by optional whitespace characters.

Decoder.ReadToken andDecoder.ReadValue calls may be interleaved.For example, the following JSON value:

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

can be parsed with the following calls (ignoring errors for brevity):

d.ReadToken() // {d.ReadToken() // "name"d.ReadToken() // "value"d.ReadValue() // "array"d.ReadToken() // [d.ReadToken() // nulld.ReadToken() // falsed.ReadValue() // trued.ReadToken() // 3.14159d.ReadToken() // ]d.ReadValue() // "object"d.ReadValue() // {"k":"v"}d.ReadToken() // }

The above is one of many possible sequence of calls andmay not represent the most sensible method to call for any given token/value.For example, it is probably more common to callDecoder.ReadToken to obtain astring token for object names.

funcNewDecoder

func NewDecoder(rio.Reader, opts ...Options) *Decoder

NewDecoder constructs a new streaming decoder reading from r.

If r is abytes.Buffer, then the decoder parses directly from the bufferwithout first copying the contents to an intermediate buffer.Additional writes to the buffer must not occur while the decoder is in use.

func (*Decoder)InputOffset

func (d *Decoder) InputOffset()int64

InputOffset returns the current input byte offset. It gives the locationof the next byte immediately after the most recently returned token or value.The number of bytes actually read from the underlyingio.Reader may be morethan this offset due to internal buffering effects.

func (*Decoder)Options

func (d *Decoder) Options()Options

Options returns the options used to construct the encoder andmay additionally contain semantic options passed to aencoding/json/v2.UnmarshalDecode call.

If operating withinaencoding/json/v2.UnmarshalerFrom.UnmarshalJSONFrom method call oraencoding/json/v2.UnmarshalFromFunc function call,then the returned options are only valid within the call.

func (*Decoder)PeekKind

func (d *Decoder) PeekKind()Kind

PeekKind retrieves the next token kind, but does not advance the read offset.

It returns 0 if an error occurs. Any such error is cached untilthe next read call and it is the caller's responsibility to eventuallyfollow up a PeekKind call with a read call.

func (*Decoder)ReadToken

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

ReadToken reads the nextToken, advancing the read offset.The returned token is only valid until the next Peek, Read, or Skip call.It returnsio.EOF if there are no more tokens.

func (*Decoder)ReadValue

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

ReadValue returns the next raw JSON value, advancing the read offset.The value is stripped of any leading or trailing whitespace andcontains the exact bytes of the input, which may contain invalid UTF-8ifAllowInvalidUTF8 is specified.

The returned value is only valid until the next Peek, Read, or Skip call andmay not be mutated while the Decoder remains in use.If the decoder is currently at the end token for an object or array,then it reports aSyntacticError and the internal state remains unchanged.It returnsio.EOF if there are no more values.

func (*Decoder)Reset

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

Reset resets a decoder such that it is reading afresh from r andconfigured with the provided options. Reset must not be called on ana Decoder passed to theencoding/json/v2.UnmarshalerFrom.UnmarshalJSONFrom methodor theencoding/json/v2.UnmarshalFromFunc function.

func (*Decoder)SkipValue

func (d *Decoder) SkipValue()error

SkipValue is semantically equivalent to callingDecoder.ReadValue and discardingthe result except that memory is not wasted trying to hold the entire result.

func (*Decoder)StackDepth

func (d *Decoder) StackDepth()int

StackDepth returns the depth of the state machine for read JSON data.Each level on the stack represents a nested JSON object or array.It is incremented whenever anBeginObject orBeginArray token is encounteredand decremented whenever anEndObject orEndArray token is encountered.The depth is zero-indexed, where zero represents the top-level JSON value.

func (*Decoder)StackIndex

func (d *Decoder) StackIndex(iint) (Kind,int64)

StackIndex returns information about the specified stack level.It must be a number between 0 andDecoder.StackDepth, inclusive.For each level, it reports the kind:

  • 0 for a level of zero,
  • '{' for a level representing a JSON object, and
  • '[' for a level representing a JSON array.

It also reports the length of that JSON object or array.Each name and value in a JSON object is counted separately,so the effective number of members would be half the length.A complete JSON object must have an even length.

func (*Decoder)StackPointer

func (d *Decoder) StackPointer()Pointer

StackPointer returns a JSON Pointer (RFC 6901) to the most recently read value.

func (*Decoder)UnreadBuffer

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

UnreadBuffer returns the data remaining in the unread buffer,which may contain zero or more bytes.The returned buffer must not be mutated while Decoder continues to be used.The buffer contents are valid until the next Peek, Read, or Skip call.

typeEncoder

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

Encoder is a streaming encoder from raw JSON tokens and values.It is used to write a stream of top-level JSON values,each terminated with a newline character.

Encoder.WriteToken andEncoder.WriteValue calls may be interleaved.For example, the following JSON value:

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

can be composed with the following calls (ignoring errors for brevity):

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

The above is one of many possible sequence of calls andmay not represent the most sensible method to call for any given token/value.For example, it is probably more common to callEncoder.WriteToken with a stringfor object names.

funcNewEncoder

func NewEncoder(wio.Writer, opts ...Options) *Encoder

NewEncoder constructs a new streaming encoder writing to wconfigured with the provided options.It flushes the internal buffer when the buffer is sufficiently full orwhen a top-level value has been written.

If w is abytes.Buffer, then the encoder appends directly into the bufferwithout copying the contents from an intermediate buffer.

func (*Encoder)AvailableBuffer

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

AvailableBuffer returns a zero-length buffer with a possible non-zero capacity.This buffer is intended to be used to populate aValuebeing passed to an immediately succeedingEncoder.WriteValue call.

Example usage:

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

It is the user's responsibility to ensure that the value is valid JSON.

func (*Encoder)Options

func (e *Encoder) Options()Options

Options returns the options used to construct the decoder andmay additionally contain semantic options passed to aencoding/json/v2.MarshalEncode call.

If operating withinaencoding/json/v2.MarshalerTo.MarshalJSONTo method call oraencoding/json/v2.MarshalToFunc function call,then the returned options are only valid within the call.

func (*Encoder)OutputOffset

func (e *Encoder) OutputOffset()int64

OutputOffset returns the current output byte offset. It gives the locationof the next byte immediately after the most recently written token or value.The number of bytes actually written to the underlyingio.Writer may be lessthan this offset due to internal buffering effects.

func (*Encoder)Reset

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

Reset resets an encoder such that it is writing afresh to w andconfigured with the provided options. Reset must not be called ona Encoder passed to theencoding/json/v2.MarshalerTo.MarshalJSONTo methodor theencoding/json/v2.MarshalToFunc function.

func (*Encoder)StackDepth

func (e *Encoder) StackDepth()int

StackDepth returns the depth of the state machine for written JSON data.Each level on the stack represents a nested JSON object or array.It is incremented whenever anBeginObject orBeginArray token is encounteredand decremented whenever anEndObject orEndArray token is encountered.The depth is zero-indexed, where zero represents the top-level JSON value.

func (*Encoder)StackIndex

func (e *Encoder) StackIndex(iint) (Kind,int64)

StackIndex returns information about the specified stack level.It must be a number between 0 andEncoder.StackDepth, inclusive.For each level, it reports the kind:

  • 0 for a level of zero,
  • '{' for a level representing a JSON object, and
  • '[' for a level representing a JSON array.

It also reports the length of that JSON object or array.Each name and value in a JSON object is counted separately,so the effective number of members would be half the length.A complete JSON object must have an even length.

func (*Encoder)StackPointer

func (e *Encoder) StackPointer()Pointer

StackPointer returns a JSON Pointer (RFC 6901) to the most recently written value.

func (*Encoder)WriteToken

func (e *Encoder) WriteToken(tToken)error

WriteToken writes the next token and advances the internal write offset.

The provided token kind must be consistent with the JSON grammar.For example, it is an error to provide a number when the encoderis expecting an object name (which is always a string), orto provide an end object delimiter when the encoder is finishing an array.If the provided token is invalid, then it reports aSyntacticError andthe internal state remains unchanged. The offset reportedinSyntacticError will be relative to theEncoder.OutputOffset.

func (*Encoder)WriteValue

func (e *Encoder) WriteValue(vValue)error

WriteValue writes the next raw value and advances the internal write offset.The Encoder does not simply copy the provided value verbatim, butparses it to ensure that it is syntactically valid and reformats itaccording to how the Encoder is configured to format whitespace and strings.IfAllowInvalidUTF8 is specified, then any invalid UTF-8 is mangledas the Unicode replacement character, U+FFFD.

The provided value kind must be consistent with the JSON grammar(see examples onEncoder.WriteToken). If the provided value is invalid,then it reports aSyntacticError and the internal state remains unchanged.The offset reported inSyntacticError will be relative to theEncoder.OutputOffset plus the offset into v of any encountered syntax error.

typeKind

type Kindbyte

Kind represents each possible JSON token kind with a single byte,which is conveniently the first byte of that kind's grammarwith the restriction that numbers always be represented with '0':

  • 'n': null
  • 'f': false
  • 't': true
  • '"': string
  • '0': number
  • '{': object begin
  • '}': object end
  • '[': array begin
  • ']': array end

An invalid kind is usually represented using 0,but may be non-zero due to invalid JSON data.

func (Kind)String

func (kKind) String()string

String prints the kind in a humanly readable fashion.

typeOptions

type Options =jsonopts.Options

Options configuresNewEncoder,Encoder.Reset,NewDecoder,andDecoder.Reset with specific features.Each function takes in a variadic list of options, where propertiesset in latter options override the value of previously set properties.

There is a single Options type, which is used with both encoding and decoding.Some options affect both operations, while others only affect one operation:

Options that do not affect a particular operation are ignored.

The Options type is identical toencoding/json.Options andencoding/json/v2.Options. Options from the other packages maybe passed to functionality in this package, but are ignored.Options from this package may be used with the other packages.

funcAllowDuplicateNames

func AllowDuplicateNames(vbool)Options

AllowDuplicateNames specifies that JSON objects may containduplicate member names. Disabling the duplicate name check may provideperformance benefits, but breaks compliance withRFC 7493, section 2.3.The input or output will still be compliant withRFC 8259,which leaves the handling of duplicate names as unspecified behavior.

This affects either encoding or decoding.

funcAllowInvalidUTF8

func AllowInvalidUTF8(vbool)Options

AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8,which will be mangled as the Unicode replacement character, U+FFFD.This causes the encoder or decoder to break compliance withRFC 7493, section 2.1, andRFC 8259, section 8.1.

This affects either encoding or decoding.

funcCanonicalizeRawFloats

func CanonicalizeRawFloats(vbool)Options

CanonicalizeRawFloats specifies that when encoding a raw JSONfloating-point number (i.e., a number with a fraction or exponent) in aToken orValue, the number is canonicalizedaccording toRFC 8785, section 3.2.2.3. As a special case,the number -0 is canonicalized as 0.

JSON numbers are treated as IEEE 754 double precision numbers.It is safe to canonicalize a serialized single precision number andparse it back as a single precision number and expect the same value.If a number exceeds ±1.7976931348623157e+308, which is the maximumfinite number, then it saturated at that value and formatted as such.

This only affects encoding and is ignored when decoding.

funcCanonicalizeRawInts

func CanonicalizeRawInts(vbool)Options

CanonicalizeRawInts specifies that when encoding a raw JSONinteger number (i.e., a number without a fraction and exponent) in aToken orValue, the number is canonicalizedaccording toRFC 8785, section 3.2.2.3. As a special case,the number -0 is canonicalized as 0.

JSON numbers are treated as IEEE 754 double precision numbers.Any numbers with precision beyond what is representable by that formwill lose their precision when canonicalized. For example,integer values beyond ±2⁵³ will lose their precision.For example, 1234567890123456789 is formatted as 1234567890123456800.

This only affects encoding and is ignored when decoding.

funcEscapeForHTML

func EscapeForHTML(vbool)Options

EscapeForHTML specifies that '<', '>', and '&' characters within JSON stringsshould be escaped as a hexadecimal Unicode codepoint (e.g., \u003c) so thatthe output is safe to embed within HTML.

This only affects encoding and is ignored when decoding.

Example

Directly embedding JSON within HTML requires special handling for safety.Escape certain runes to prevent JSON directly treated as HTMLfrom being able to perform <script> injection.

This example shows how to obtain equivalent behavior provided by thev1encoding/json package that is no longer directly supported by this package.Newly written code that intermix JSON and HTML should instead be using thegithub.com/google/safehtml module for safety purposes.

package mainimport ("fmt""log""github.com/go-json-experiment/json""github.com/go-json-experiment/json/jsontext")func main() {page := struct {Title stringBody  string}{Title: "Example Embedded Javascript",Body:  `<script> console.log("Hello, world!"); </script>`,}b, err := json.Marshal(&page,// Escape certain runes within a JSON string so that// JSON will be safe to directly embed inside HTML.jsontext.EscapeForHTML(true),jsontext.EscapeForJS(true),jsontext.Multiline(true)) // expand for readabilityif err != nil {log.Fatal(err)}fmt.Println(string(b))}
Output:{"Title": "Example Embedded Javascript","Body": "\u003cscript\u003e console.log(\"Hello, world!\"); \u003c/script\u003e"}

funcEscapeForJS

func EscapeForJS(vbool)Options

EscapeForJS specifies that U+2028 and U+2029 characters within JSON stringsshould be escaped as a hexadecimal Unicode codepoint (e.g., \u2028) so thatthe output is valid to embed within JavaScript. SeeRFC 8259, section 12.

This only affects encoding and is ignored when decoding.

funcMultiline

func Multiline(vbool)Options

Multiline specifies that the JSON output should expand to multiple lines,where every JSON object member or JSON array element appears ona new, indented line according to the nesting depth.

IfSpaceAfterColon is not specified, then the default is true.IfSpaceAfterComma is not specified, then the default is false.IfWithIndent is not specified, then the default is "\t".

If set to false, then the output is a single-line,where the only whitespace emitted is determined by the currentvalues ofSpaceAfterColon andSpaceAfterComma.

This only affects encoding and is ignored when decoding.

funcPreserveRawStrings

func PreserveRawStrings(vbool)Options

PreserveRawStrings specifies that when encoding a raw JSON string in aToken orValue, pre-escaped sequencesin a JSON string are preserved to the output.However, raw strings still respectEscapeForHTML andEscapeForJSsuch that the relevant characters are escaped.IfAllowInvalidUTF8 is enabled, bytes of invalid UTF-8are preserved to the output.

This only affects encoding and is ignored when decoding.

funcReorderRawObjects

func ReorderRawObjects(vbool)Options

ReorderRawObjects specifies that when encoding a raw JSON object in aValue, the object members are reordered according toRFC 8785, section 3.2.3.

This only affects encoding and is ignored when decoding.

funcSpaceAfterColon

func SpaceAfterColon(vbool)Options

SpaceAfterColon specifies that the JSON output should emit a space characterafter each colon separator following a JSON object name.If false, then no space character appears after the colon separator.

This only affects encoding and is ignored when decoding.

funcSpaceAfterComma

func SpaceAfterComma(vbool)Options

SpaceAfterComma specifies that the JSON output should emit a space characterafter each comma separator following a JSON object value or array element.If false, then no space character appears after the comma separator.

This only affects encoding and is ignored when decoding.

funcWithIndent

func WithIndent(indentstring)Options

WithIndent specifies that the encoder should emit multiline outputwhere each element in a JSON object or array begins on a new, indented linebeginning with the indent prefix (seeWithIndentPrefix)followed by one or more copies of indent according to the nesting depth.The indent must only be composed of space or tab characters.

If the intent to emit indented output without a preference forthe particular indent string, then useMultiline instead.

This only affects encoding and is ignored when decoding.Use of this option impliesMultiline being set to true.

funcWithIndentPrefix

func WithIndentPrefix(prefixstring)Options

WithIndentPrefix specifies that the encoder should emit multiline outputwhere each element in a JSON object or array begins on a new, indented linebeginning with the indent prefix followed by one or more copies of indent(seeWithIndent) according to the nesting depth.The prefix must only be composed of space or tab characters.

This only affects encoding and is ignored when decoding.Use of this option impliesMultiline being set to true.

typePointer

type Pointerstring

Pointer is a JSON Pointer (RFC 6901) that references a particular JSON valuerelative to the root of the top-level JSON value.

A Pointer is a slash-separated list of tokens, where each token iseither a JSON object name or an index to a JSON array elementencoded as a base-10 integer value.It is impossible to distinguish between an array index and an object name(that happens to be an base-10 encoded integer) without also knowingthe structure of the top-level JSON value that the pointer refers to.

There is exactly one representation of a pointer to a particular value,so comparability of Pointer values is equivalent to checking whetherthey both point to the exact same value.

func (Pointer)AppendToken

func (pPointer) AppendToken(tokstring)Pointer

AppendToken appends a token to the end of p and returns the full pointer.

func (Pointer)Contains

func (pPointer) Contains(pcPointer)bool

Contains reports whether the JSON value that p points tois equal to or contains the JSON value that pc points to.

func (Pointer)IsValid

func (pPointer) IsValid()bool

IsValid reports whether p is a valid JSON Pointer according toRFC 6901.Note that the concatenation of two valid pointers produces a valid pointer.

func (Pointer)LastToken

func (pPointer) LastToken()string

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

func (Pointer)Parent

func (pPointer) Parent()Pointer

Parent strips off the last token and returns the remaining pointer.The parent of an empty p is an empty string.

func (Pointer)Tokens

func (pPointer) Tokens()iter.Seq[string]

Tokens returns an iterator over the reference tokens in the JSON pointer,starting from the first token until the last token (unless stopped early).

typeSyntacticError

type SyntacticError struct {// ByteOffset indicates that an error occurred after this byte offset.ByteOffsetint64// JSONPointer indicates that an error occurred within this JSON value// as indicated using the JSON Pointer notation (seeRFC 6901).JSONPointerPointer// Err is the underlying error.Errerror// contains filtered or unexported fields}

SyntacticError is a description of a syntactic error that occurred whenencoding or decoding JSON according to the grammar.

The contents of this error as produced by this package may change over time.

func (*SyntacticError)Error

func (e *SyntacticError) Error()string

func (*SyntacticError)Unwrap

func (e *SyntacticError) Unwrap()error

typeToken

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

Token represents a lexical JSON token, which may be one of the following:

  • 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 for a JSON object (i.e., { or } )
  • a begin or end delimiter for a JSON array (i.e., [ or ] )

A Token cannot represent entire array or object values, while aValue can.There is no Token to represent commas and colons sincethese structural tokens can be inferred from the surrounding context.

var (NullToken = rawToken("null")FalseToken = rawToken("false")TrueToken = rawToken("true")BeginObjectToken = rawToken("{")EndObjectToken = rawToken("}")BeginArrayToken = rawToken("[")EndArrayToken = rawToken("]"))

funcBool

func Bool(bbool)Token

Bool constructs a Token representing a JSON boolean.

funcFloat

func Float(nfloat64)Token

Float constructs a Token representing a JSON number.The values NaN, +Inf, and -Inf will be representedas a JSON string with the values "NaN", "Infinity", and "-Infinity".

funcInt

func Int(nint64)Token

Int constructs a Token representing a JSON number from an int64.

funcString

func String(sstring)Token

String constructs a Token representing a JSON string.The provided string should contain valid UTF-8, otherwise invalid charactersmay be mangled as the Unicode replacement character.

funcUint

func Uint(nuint64)Token

Uint constructs a Token representing a JSON number from a uint64.

func (Token)Bool

func (tToken) Bool()bool

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

func (Token)Clone

func (tToken) Clone()Token

Clone makes a copy of the Token such that its value remains valideven after a subsequent [Decoder.Read] call.

func (Token)Float

func (tToken) Float()float64

Float returns the floating-point value for a JSON number.It returns a NaN, +Inf, or -Inf value for any JSON stringwith the values "NaN", "Infinity", or "-Infinity".It panics for all other cases.

func (Token)Int

func (tToken) Int()int64

Int returns the signed integer value for a JSON number.The fractional component of any number is ignored (truncation toward zero).Any number beyond the representation of an int64 will be saturatedto the closest representable value.It panics if the token kind is not a JSON number.

func (Token)Kind

func (tToken) Kind()Kind

Kind returns the token kind.

func (Token)String

func (tToken) String()string

String returns the unescaped string value for a JSON string.For other JSON kinds, this returns the raw JSON representation.

func (Token)Uint

func (tToken) Uint()uint64

Uint returns the unsigned integer value for a JSON number.The fractional component of any number is ignored (truncation toward zero).Any number beyond the representation of an uint64 will be saturatedto the closest representable value.It panics if the token kind is not a JSON number.

typeValue

type Value []byte

Value represents a single raw JSON value, which may be one of the following:

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

Value can represent entire array or object values, whileToken cannot.Value may contain leading and/or trailing whitespace.

func (*Value)Canonicalize

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

Canonicalize canonicalizes the raw JSON value according to theJSON Canonicalization Scheme (JCS) as defined byRFC 8785where it produces a stable representation of a JSON value.

JSON strings are formatted to use their minimal representation,JSON numbers are formatted as double precision numbers accordingto some stable serialization algorithm.JSON object members are sorted in ascending order by name.All whitespace is removed.

The output stability is dependent on the stability of the application data(seeRFC 8785, Appendix E). It cannot produce stable output fromfundamentally unstable input. For example, if the JSON valuecontains ephemeral data (e.g., a frequently changing timestamp),then the value is still unstable regardless of whether this is called.

Canonicalize is equivalent to callingValue.Format with the following options:

Any options specified by the caller are applied after the initial setand may deliberately override prior options.

Note that JCS treats all JSON numbers as IEEE 754 double precision numbers.Any numbers with precision beyond what is representable by that formwill lose their precision when canonicalized. For example, integer valuesbeyond ±2⁵³ will lose their precision. To preserve the original representationof JSON integers, additionally setCanonicalizeRawInts to false:

v.Canonicalize(jsontext.CanonicalizeRawInts(false))

func (Value)Clone

func (vValue) Clone()Value

Clone returns a copy of v.

func (*Value)Compact

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

Compact removes all whitespace from the raw JSON value.

It does not reformat JSON strings or numbers to use any other representation.To maximize the set of JSON values that can be formatted,this permits values with duplicate names and invalid UTF-8.

Compact is equivalent to callingValue.Format with the following options:

Any options specified by the caller are applied after the initial setand may deliberately override prior options.

func (*Value)Format

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

Format formats the raw JSON value in place.

By default (if no options are specified), it validates according toRFC 7493and produces the minimal JSON representation, whereall whitespace is elided and JSON strings use the shortest encoding.

Relevant options include:

All other options are ignored.

It is guaranteed to succeed if the value is valid according to the same options.If the value is already formatted, then the buffer is not mutated.

func (*Value)Indent

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

Indent reformats the whitespace in the raw JSON value so that each elementin a JSON object or array begins on a indented line according to the nesting.

It does not reformat JSON strings or numbers to use any other representation.To maximize the set of JSON values that can be formatted,this permits values with duplicate names and invalid UTF-8.

Indent is equivalent to callingValue.Format with the following options:

Any options specified by the caller are applied after the initial setand may deliberately override prior options.

func (Value)IsValid

func (vValue) IsValid(opts ...Options)bool

IsValid reports whether the raw JSON value is syntactically validaccording to the specified options.

By default (if no options are specified), it validates according toRFC 7493.It verifies whether the input is properly encoded as UTF-8,that escape sequences within strings decode to valid Unicode codepoints, andthat all names in each object are unique.It does not verify whether numbers are representable within the limitsof any common numeric type (e.g., float64, int64, or uint64).

Relevant options include:

All other options are ignored.

func (Value)Kind

func (vValue) Kind()Kind

Kind returns the starting token kind.For a valid value, this will never include '}' or ']'.

func (Value)MarshalJSON

func (vValue) MarshalJSON() ([]byte,error)

MarshalJSON returns v as the JSON encoding of v.It returns the stored value as the raw JSON output without any validation.If v is nil, then this returns a JSON null.

func (Value)String

func (vValue) String()string

String returns the string formatting of v.

func (*Value)UnmarshalJSON

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

UnmarshalJSON sets v as the JSON encoding of b.It stores a copy of the provided raw JSON input without any validation.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp