Involved Source Filesdecode.go Package json implements encoding and decoding of JSON as defined in
RFC 7159. The mapping between JSON and Go values is described
in the documentation for the Marshal and Unmarshal functions.
See "JSON and Go" for an introduction to this package:
https://golang.org/doc/articles/json_and_go.htmlfold.goindent.goscanner.gostream.gotables.gotags.go
Code Examples
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"strings"
)
func main() {
const jsonStream = `
{"Name": "Ed", "Text": "Knock knock."}
{"Name": "Sam", "Text": "Who's there?"}
{"Name": "Ed", "Text": "Go fmt."}
{"Name": "Sam", "Text": "Go fmt who?"}
{"Name": "Ed", "Text": "Go fmt yourself!"}
`
type Message struct {
Name, Text string
}
dec := json.NewDecoder(strings.NewReader(jsonStream))
for {
var m Message
if err := dec.Decode(&m); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Printf("%s: %s\n", m.Name, m.Text)
}
}
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
)
func main() {
const jsonStream = `
[
{"Name": "Ed", "Text": "Knock knock."},
{"Name": "Sam", "Text": "Who's there?"},
{"Name": "Ed", "Text": "Go fmt."},
{"Name": "Sam", "Text": "Go fmt who?"},
{"Name": "Ed", "Text": "Go fmt yourself!"}
]
`
type Message struct {
Name, Text string
}
dec := json.NewDecoder(strings.NewReader(jsonStream))
// read open bracket
t, err := dec.Token()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%T: %v\n", t, t)
// while the array contains values
for dec.More() {
var m Message
// decode an array value (Message)
err := dec.Decode(&m)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v: %v\n", m.Name, m.Text)
}
// read closing bracket
t, err = dec.Token()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%T: %v\n", t, t)
}
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"strings"
)
func main() {
const jsonStream = `
{"Message": "Hello", "Array": [1, 2, 3], "Null": null, "Number": 1.234}
`
dec := json.NewDecoder(strings.NewReader(jsonStream))
for {
t, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
fmt.Printf("%T: %v", t, t)
if dec.More() {
fmt.Printf(" (more)")
}
fmt.Printf("\n")
}
}
package main
import (
"bytes"
"encoding/json"
"os"
)
func main() {
var out bytes.Buffer
json.HTMLEscape(&out, []byte(`{"Name":"<b>HTML content</b>"}`))
out.WriteTo(os.Stdout)
}
package main
import (
"bytes"
"encoding/json"
"log"
"os"
)
func main() {
type Road struct {
Name string
Number int
}
roads := []Road{
{"Diamond Fork", 29},
{"Sheep Creek", 51},
}
b, err := json.Marshal(roads)
if err != nil {
log.Fatal(err)
}
var out bytes.Buffer
json.Indent(&out, b, "=", "\t")
out.WriteTo(os.Stdout)
}
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
type ColorGroup struct {
ID int
Name string
Colors []string
}
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := json.Marshal(group)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
}
package main
import (
"encoding/json"
"fmt"
"log"
)
func main() {
data := map[string]int{
"a": 1,
"b": 2,
}
b, err := json.MarshalIndent(data, "<prefix>", "<indent>")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(b))
}
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
h := json.RawMessage(`{"precomputed": true}`)
c := struct {
Header *json.RawMessage `json:"header"`
Body string `json:"body"`
}{Header: &h, Body: "Hello Gophers!"}
b, err := json.MarshalIndent(&c, "", "\t")
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
}
package main
import (
"encoding/json"
"fmt"
"log"
)
func main() {
type Color struct {
Space string
Point json.RawMessage // delay parsing until we know the color space
}
type RGB struct {
R uint8
G uint8
B uint8
}
type YCbCr struct {
Y uint8
Cb int8
Cr int8
}
var j = []byte(`[
{"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
{"Space": "RGB", "Point": {"R": 98, "G": 218, "B": 255}}
]`)
var colors []Color
err := json.Unmarshal(j, &colors)
if err != nil {
log.Fatalln("error:", err)
}
for _, c := range colors {
var dst any
switch c.Space {
case "RGB":
dst = new(RGB)
case "YCbCr":
dst = new(YCbCr)
}
err := json.Unmarshal(c.Point, dst)
if err != nil {
log.Fatalln("error:", err)
}
fmt.Println(c.Space, dst)
}
}
package main
import (
"encoding/json"
"fmt"
)
func main() {
var jsonBlob = []byte(`[
{"Name": "Platypus", "Order": "Monotremata"},
{"Name": "Quoll", "Order": "Dasyuromorphia"}
]`)
type Animal struct {
Name string
Order string
}
var animals []Animal
err := json.Unmarshal(jsonBlob, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", animals)
}
package main
import (
"encoding/json"
"fmt"
)
func main() {
goodJSON := `{"example": 1}`
badJSON := `{"example":2:]}}`
fmt.Println(json.Valid([]byte(goodJSON)), json.Valid([]byte(badJSON)))
}
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
)
type Animal int
const (
Unknown Animal = iota
Gopher
Zebra
)
func (a *Animal) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
switch strings.ToLower(s) {
default:
*a = Unknown
case "gopher":
*a = Gopher
case "zebra":
*a = Zebra
}
return nil
}
func (a Animal) MarshalJSON() ([]byte, error) {
var s string
switch a {
default:
s = "unknown"
case Gopher:
s = "gopher"
case Zebra:
s = "zebra"
}
return json.Marshal(s)
}
func main() {
blob := `["gopher","armadillo","zebra","unknown","gopher","bee","gopher","zebra"]`
var zoo []Animal
if err := json.Unmarshal([]byte(blob), &zoo); err != nil {
log.Fatal(err)
}
census := make(map[Animal]int)
for _, animal := range zoo {
census[animal] += 1
}
fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras: %d\n* Unknown: %d\n",
census[Gopher], census[Zebra], census[Unknown])
}
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
)
type Size int
const (
Unrecognized Size = iota
Small
Large
)
func (s *Size) UnmarshalText(text []byte) error {
switch strings.ToLower(string(text)) {
default:
*s = Unrecognized
case "small":
*s = Small
case "large":
*s = Large
}
return nil
}
func (s Size) MarshalText() ([]byte, error) {
var name string
switch s {
default:
name = "unrecognized"
case Small:
name = "small"
case Large:
name = "large"
}
return []byte(name), nil
}
func main() {
blob := `["small","regular","large","unrecognized","small","normal","small","large"]`
var inventory []Size
if err := json.Unmarshal([]byte(blob), &inventory); err != nil {
log.Fatal(err)
}
counts := make(map[Size]int)
for _, size := range inventory {
counts[size] += 1
}
fmt.Printf("Inventory Counts:\n* Small: %d\n* Large: %d\n* Unrecognized: %d\n",
counts[Small], counts[Large], counts[Unrecognized])
}
Package-Level Type Names (total 36, in which 16 are exported)
/* sort exporteds by: | */
A Decoder reads and decodes JSON values from an input stream.buf[]byteddecodeStateerrerrorrio.Readerscanscanner // amount of data already scanned // start of unread data in buftokenStack[]inttokenStateint Buffered returns a reader of the data remaining in the Decoder's
buffer. The reader is valid until the next call to Decode. Decode reads the next JSON-encoded value from its
input and stores it in the value pointed to by v.
See the documentation for Unmarshal for details about
the conversion of JSON into a Go value. DisallowUnknownFields causes the Decoder to return an error when the destination
is a struct and the input contains object keys which do not match any
non-ignored, exported fields in the destination. InputOffset returns the input stream byte offset of the current decoder position.
The offset gives the location of the end of the most recently returned token
and the beginning of the next token. More reports whether there is another element in the
current array or object being parsed. Token returns the next JSON token in the input stream.
At the end of the input stream, Token returns nil, io.EOF.
Token guarantees that the delimiters [ ] { } it returns are
properly nested and matched: if Token encounters an unexpected
delimiter in the input, it will return an error.
The input stream consists of basic JSON values—bool, string,
number, and null—along with delimiters [ ] { } of type Delim
to mark the start and end of arrays and objects.
Commas and colons are elided. UseNumber causes the Decoder to unmarshal a number into an interface{} as a
Number instead of as a float64.(*Decoder) peek() (byte, error) readValue reads a JSON value into dec.buf.
It returns the length of the encoding.(*Decoder) refill() error(*Decoder) tokenError(c byte) (Token, error) advance tokenstate from a separator state to a value state(*Decoder) tokenValueAllowed() bool(*Decoder) tokenValueEnd()
func NewDecoder(r io.Reader) *Decoder
A Delim is a JSON array or object delimiter, one of [ ] { or }.( Delim) String() string
Delim : fmt.Stringer
Delim : context.stringer
Delim : runtime.stringer
An Encoder writes JSON values to an output stream.errerrorescapeHTMLboolindentBuf[]byteindentPrefixstringindentValuestringwio.Writer Encode writes the JSON encoding of v to the stream,
followed by a newline character.
See the documentation for Marshal for details about the
conversion of Go values to JSON. SetEscapeHTML specifies whether problematic HTML characters
should be escaped inside JSON quoted strings.
The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e
to avoid certain safety problems that can arise when embedding JSON in HTML.
In non-HTML settings where the escaping interferes with the readability
of the output, SetEscapeHTML(false) disables this behavior. SetIndent instructs the encoder to format each subsequent encoded
value as if indented by the package-level function Indent(dst, src, prefix, indent).
Calling SetIndent("", "") disables indentation.
*Encoder : go.uber.org/zap/zapcore.ReflectedEncoder
func NewEncoder(w io.Writer) *Encoder
An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
(The argument to Unmarshal must be a non-nil pointer.)Typereflect.Type(*InvalidUnmarshalError) Error() string
*InvalidUnmarshalError : error
Before Go 1.2, an InvalidUTF8Error was returned by Marshal when
attempting to encode a string value with invalid UTF-8 sequences.
As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by
replacing invalid bytes with the Unicode replacement rune U+FFFD.
Deprecated: No longer used; kept for compatibility. // the whole string value that caused the error(*InvalidUTF8Error) Error() string
*InvalidUTF8Error : error
Marshaler is the interface implemented by types that
can marshal themselves into valid JSON.( Marshaler) MarshalJSON() ([]byte, error)RawMessage
github.com/gotd/td/internal/crypto.AuthKey
*go.opentelemetry.io/otel/attribute.Set
go.opentelemetry.io/otel/attribute.Value
*go.opentelemetry.io/otel/codes.Code
go.opentelemetry.io/otel/trace.SpanContext
go.opentelemetry.io/otel/trace.SpanID
go.opentelemetry.io/otel/trace.TraceFlags
go.opentelemetry.io/otel/trace.TraceID
go.opentelemetry.io/otel/trace.TraceState
*go.uber.org/atomic.Bool
*go.uber.org/atomic.Duration
*go.uber.org/atomic.Float32
*go.uber.org/atomic.Float64
*go.uber.org/atomic.Int32
*go.uber.org/atomic.Int64
*go.uber.org/atomic.Uint32
*go.uber.org/atomic.Uint64
*go.uber.org/atomic.Uintptr
*math/big.Int
time.Time
A MarshalerError represents an error from calling a MarshalJSON or MarshalText method.ErrerrorTypereflect.TypesourceFuncstring(*MarshalerError) Error() string Unwrap returns the underlying error.
*MarshalerError : error
*MarshalerError : github.com/go-faster/errors.Wrapper
A Number represents a JSON number literal. Float64 returns the number as a float64. Int64 returns the number as an int64. String returns the literal text of the number.
Number : fmt.Stringer
Number : context.stringer
Number : runtime.stringer
RawMessage is a raw encoded JSON value.
It implements Marshaler and Unmarshaler and can
be used to delay JSON decoding or precompute a JSON encoding. MarshalJSON returns m as the JSON encoding of m. UnmarshalJSON sets *m to a copy of data.
RawMessage : Marshaler
*RawMessage : Unmarshaler
A SyntaxError is a description of a JSON syntax error.
Unmarshal will return a SyntaxError if the JSON can't be parsed. // error occurred after reading Offset bytes // description of error(*SyntaxError) Error() string
*SyntaxError : error
A Token holds a value of one of these types:
Delim, for the four JSON delimiters [ ] { }
bool, for JSON booleans
float64, for JSON numbers
Number, for JSON numbers
string, for JSON string literals
nil, for JSON null
func (*Decoder).Token() (Token, error)
func (*Decoder).tokenError(c byte) (Token, error)
Unmarshaler is the interface implemented by types
that can unmarshal a JSON description of themselves.
The input can be assumed to be a valid encoding of
a JSON value. UnmarshalJSON must copy the JSON data
if it wishes to retain the data after returning.
By convention, to approximate the behavior of Unmarshal itself,
Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.( Unmarshaler) UnmarshalJSON([]byte) error
*RawMessage
*github.com/gotd/td/internal/crypto.AuthKey
*go.opentelemetry.io/otel/codes.Code
*go.uber.org/atomic.Bool
*go.uber.org/atomic.Duration
*go.uber.org/atomic.Float32
*go.uber.org/atomic.Float64
*go.uber.org/atomic.Int32
*go.uber.org/atomic.Int64
*go.uber.org/atomic.Uint32
*go.uber.org/atomic.Uint64
*go.uber.org/atomic.Uintptr
*go.uber.org/zap/zapcore.TimeEncoder
*math/big.Int
*time.Time
func indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value)
An UnmarshalFieldError describes a JSON object key that
led to an unexported (and therefore unwritable) struct field.
Deprecated: No longer used; kept for compatibility.Fieldreflect.StructFieldKeystringTypereflect.Type(*UnmarshalFieldError) Error() string
*UnmarshalFieldError : error
An UnmarshalTypeError describes a JSON value that was
not appropriate for a value of a specific Go type. // the full path from root node to the field // error occurred after reading Offset bytes // name of the struct type containing the field // type of Go value it could not be assigned to // description of JSON value - "bool", "array", "number -5"(*UnmarshalTypeError) Error() string
*UnmarshalTypeError : error
An UnsupportedTypeError is returned by Marshal when attempting
to encode an unsupported value type.Typereflect.Type(*UnsupportedTypeError) Error() string
*UnsupportedTypeError : error
An UnsupportedValueError is returned by Marshal when attempting
to encode an unsupported value.StrstringValuereflect.Value(*UnsupportedValueError) Error() string
*UnsupportedValueError : error
decodeState represents the state while decoding a JSON value.data[]bytedisallowUnknownFieldsboolerrorContext*errorContext // next read offset in data // last read resultsavedErrorerrorscanscanneruseNumberbool addErrorContext returns a new error enhanced with information from d.errorContext array consumes an array from d.data[d.off-1:], decoding into v.
The first byte of the array ('[') has been read already. arrayInterface is like array but returns []interface{}. convertNumber converts the number literal s to a float64 or a Number
depending on the setting of d.useNumber.(*decodeState) init(data []byte) *decodeState literalInterface consumes and returns a literal from d.data[d.off-1:] and
it reads the following byte ahead. The first byte of the literal has been
read already (that's how the caller knows it's a literal). literalStore decodes a literal stored in item into v.
fromQuoted indicates whether this literal came from unwrapping a
string from the ",string" struct tag option. this is used only to
produce more helpful error messages. object consumes an object from d.data[d.off-1:], decoding into v.
The first byte ('{') of the object has been read already. objectInterface is like object but returns map[string]interface{}. readIndex returns the position of the last byte read. rescanLiteral is similar to scanWhile(scanContinue), but it specialises the
common case where we're decoding a literal. The decoder scans the input
twice, once for syntax errors and to check the length of the value, and the
second to perform the decoding.
Only in the second step do we use decodeState to tokenize literals, so we
know there aren't any syntax errors. We can take advantage of that knowledge,
and scan a literal's bytes much more quickly. saveError saves the first err it is called with,
for reporting at the end of the unmarshal. scanNext processes the byte at d.data[d.off]. scanWhile processes bytes in d.data[d.off:] until it
receives a scan code not equal to op. skip scans to the end of what was started.(*decodeState) unmarshal(v any) error value consumes a JSON value from d.data[d.off-1:], decoding into v, and
reads the following byte ahead. If v is invalid, the value is discarded.
The first byte of the value has been read already. valueInterface is like value but returns interface{} valueQuoted is like value but decodes a
quoted string literal or literal null into an interface value.
If it finds anything other than a quoted string literal or null,
valueQuoted returns unquotedValue{}.
An encodeState encodes JSON into a bytes.Buffer. // accumulated output // contents are the bytes buf[off : len(buf)] // last read operation, so that Unread* can work correctly. // read at &buf[off], write at &buf[len(buf)] Keep track of what pointers we've seen in the current recursive call
path, to avoid cycles that could lead to a stack overflow. Only do
the relatively expensive map operations if ptrLevel is larger than
startDetectingCyclesAfter, so that we skip the work if we're within a
reasonable amount of nested pointers deep.ptrSeenmap[any]struct{} Available returns how many bytes are unused in the buffer. AvailableBuffer returns an empty buffer with b.Available() capacity.
This buffer is intended to be appended to and
passed to an immediately succeeding Write call.
The buffer is only valid until the next write operation on b. Bytes returns a slice of length b.Len() holding the unread portion of the buffer.
The slice is valid for use only until the next buffer modification (that is,
only until the next call to a method like Read, Write, Reset, or Truncate).
The slice aliases the buffer content at least until the next buffer modification,
so immediate changes to the slice will affect the result of future reads. Cap returns the capacity of the buffer's underlying byte slice, that is, the
total space allocated for the buffer's data. Grow grows the buffer's capacity, if necessary, to guarantee space for
another n bytes. After Grow(n), at least n bytes can be written to the
buffer without another allocation.
If n is negative, Grow will panic.
If the buffer can't grow it will panic with ErrTooLarge. Len returns the number of bytes of the unread portion of the buffer;
b.Len() == len(b.Bytes()). Next returns a slice containing the next n bytes from the buffer,
advancing the buffer as if the bytes had been returned by Read.
If there are fewer than n bytes in the buffer, Next returns the entire buffer.
The slice is only valid until the next call to a read or write method. Read reads the next len(p) bytes from the buffer or until the buffer
is drained. The return value n is the number of bytes read. If the
buffer has no data to return, err is io.EOF (unless len(p) is zero);
otherwise it is nil. ReadByte reads and returns the next byte from the buffer.
If no byte is available, it returns error io.EOF. ReadBytes reads until the first occurrence of delim in the input,
returning a slice containing the data up to and including the delimiter.
If ReadBytes encounters an error before finding a delimiter,
it returns the data read before the error and the error itself (often io.EOF).
ReadBytes returns err != nil if and only if the returned data does not end in
delim. ReadFrom reads data from r until EOF and appends it to the buffer, growing
the buffer as needed. The return value n is the number of bytes read. Any
error except io.EOF encountered during the read is also returned. If the
buffer becomes too large, ReadFrom will panic with ErrTooLarge. ReadRune reads and returns the next UTF-8-encoded
Unicode code point from the buffer.
If no bytes are available, the error returned is io.EOF.
If the bytes are an erroneous UTF-8 encoding, it
consumes one byte and returns U+FFFD, 1. ReadString reads until the first occurrence of delim in the input,
returning a string containing the data up to and including the delimiter.
If ReadString encounters an error before finding a delimiter,
it returns the data read before the error and the error itself (often io.EOF).
ReadString returns err != nil if and only if the returned data does not end
in delim. Reset resets the buffer to be empty,
but it retains the underlying storage for use by future writes.
Reset is the same as Truncate(0). String returns the contents of the unread portion of the buffer
as a string. If the Buffer is a nil pointer, it returns "<nil>".
To build strings more efficiently, see the strings.Builder type. Truncate discards all but the first n unread bytes from the buffer
but continues to use the same allocated storage.
It panics if n is negative or greater than the length of the buffer. UnreadByte unreads the last byte returned by the most recent successful
read operation that read at least one byte. If a write has happened since
the last read, if the last read returned an error, or if the read read zero
bytes, UnreadByte returns an error. UnreadRune unreads the last rune returned by ReadRune.
If the most recent read or write operation on the buffer was
not a successful ReadRune, UnreadRune returns an error. (In this regard
it is stricter than UnreadByte, which will unread the last byte
from any read operation.) Write appends the contents of p to the buffer, growing the buffer as
needed. The return value n is the length of p; err is always nil. If the
buffer becomes too large, Write will panic with ErrTooLarge. WriteByte appends the byte c to the buffer, growing the buffer as needed.
The returned error is always nil, but is included to match bufio.Writer's
WriteByte. If the buffer becomes too large, WriteByte will panic with
ErrTooLarge. WriteRune appends the UTF-8 encoding of Unicode code point r to the
buffer, returning its length and an error, which is always nil but is
included to match bufio.Writer's WriteRune. The buffer is grown as needed;
if it becomes too large, WriteRune will panic with ErrTooLarge. WriteString appends the contents of s to the buffer, growing the buffer as
needed. The return value n is the length of s; err is always nil. If the
buffer becomes too large, WriteString will panic with ErrTooLarge. WriteTo writes data to w until the buffer is drained or an error occurs.
The return value n is the number of bytes written; it always fits into an
int, but it is int64 to match the io.WriterTo interface. Any error
encountered during the write is also returned. empty reports whether the unread portion of the buffer is empty. error aborts the encoding by panicking with err wrapped in jsonError. grow grows the buffer to guarantee space for n more bytes.
It returns the index where bytes should be written.
If the buffer can't grow it will panic with ErrTooLarge.(*encodeState) marshal(v any, opts encOpts) (err error) readSlice is like ReadBytes but returns a reference to internal buffer data.(*encodeState) reflectValue(v reflect.Value, opts encOpts) tryGrowByReslice is an inlineable version of grow for the fast-case where the
internal buffer only needs to be resliced.
It returns the index where bytes should be written and whether it succeeded.
*encodeState : compress/flate.Reader
*encodeState : fmt.Stringer
*encodeState : github.com/klauspost/compress/flate.Reader
*encodeState : internal/bisect.Writer
*encodeState : io.ByteReader
*encodeState : io.ByteScanner
*encodeState : io.ByteWriter
*encodeState : io.Reader
*encodeState : io.ReaderFrom
*encodeState : io.ReadWriter
*encodeState : io.RuneReader
*encodeState : io.RuneScanner
*encodeState : io.StringWriter
*encodeState : io.Writer
*encodeState : io.WriterTo
*encodeState : context.stringer
*encodeState : crypto/tls.transcriptHash
*encodeState : net/http.http2pipeBuffer
*encodeState : net/http.http2stringWriter
*encodeState : runtime.stringer
func newEncodeState() *encodeState
func addrMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts)
func addrTextMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts)
func boolEncoder(e *encodeState, v reflect.Value, opts encOpts)
func encodeByteSlice(e *encodeState, v reflect.Value, _ encOpts)
func intEncoder(e *encodeState, v reflect.Value, opts encOpts)
func interfaceEncoder(e *encodeState, v reflect.Value, opts encOpts)
func invalidValueEncoder(e *encodeState, v reflect.Value, _ encOpts)
func marshalerEncoder(e *encodeState, v reflect.Value, opts encOpts)
func stringEncoder(e *encodeState, v reflect.Value, opts encOpts)
func textMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts)
func uintEncoder(e *encodeState, v reflect.Value, opts encOpts)
func unsupportedTypeEncoder(e *encodeState, v reflect.Value, _ encOpts)
jsonError is an error wrapper type for internal use only.
Panics with errors are wrapped in jsonError so that the top-level recover
can distinguish intentional panics from this package.errorerror( jsonError) Error() builtin.string
jsonError : error
A scanner is a JSON scanning state machine.
Callers call scan.reset and then pass bytes in one at a time
by calling scan.step(&scan, c) for each byte.
The return value, referred to as an opcode, tells the
caller about significant parsing events like beginning
and ending literals, objects, and arrays, so that the
caller can follow along if it wishes.
The return value scanEnd indicates that a single top-level
JSON value has been completed, *before* the byte that
just got passed in. (The indication must be delayed in order
to recognize the end of numbers: is 123 a whole value or
the beginning of 12345e+6?). total bytes consumed, updated by decoder.Decode (and deliberately
not set to zero by scan.reset) Reached end of top-level value. Error that happened, if any. Stack of what we're in the middle of - array values, object keys, object values. The step is a func to be called to execute the next transition.
Also tried using an integer constant and a single func
with a switch, but using the func directly was 10% faster
on a 64-bit Mac Mini, and it's nicer to read. eof tells the scanner that the end of input has been reached.
It returns a scan status just as s.step does. error records an error and switches to the error state. popParseState pops a parse state (already obtained) off the stack
and updates s.step accordingly. pushParseState pushes a new parse state p onto the parse stack.
an error state is returned if maxNestingDepth was exceeded, otherwise successState is returned. reset prepares the scanner for use.
It must be called before calling s.step.
func newScanner() *scanner
func checkValid(data []byte, scan *scanner) error
func freeScanner(scan *scanner)
func state0(s *scanner, c byte) int
func state1(s *scanner, c byte) int
func stateBeginString(s *scanner, c byte) int
func stateBeginStringOrEmpty(s *scanner, c byte) int
func stateBeginValue(s *scanner, c byte) int
func stateBeginValueOrEmpty(s *scanner, c byte) int
func stateDot(s *scanner, c byte) int
func stateDot0(s *scanner, c byte) int
func stateE(s *scanner, c byte) int
func stateE0(s *scanner, c byte) int
func stateEndTop(s *scanner, c byte) int
func stateEndValue(s *scanner, c byte) int
func stateError(s *scanner, c byte) int
func stateESign(s *scanner, c byte) int
func stateF(s *scanner, c byte) int
func stateFa(s *scanner, c byte) int
func stateFal(s *scanner, c byte) int
func stateFals(s *scanner, c byte) int
func stateInString(s *scanner, c byte) int
func stateInStringEsc(s *scanner, c byte) int
func stateInStringEscU(s *scanner, c byte) int
func stateInStringEscU1(s *scanner, c byte) int
func stateInStringEscU12(s *scanner, c byte) int
func stateInStringEscU123(s *scanner, c byte) int
func stateN(s *scanner, c byte) int
func stateNeg(s *scanner, c byte) int
func stateNu(s *scanner, c byte) int
func stateNul(s *scanner, c byte) int
func stateT(s *scanner, c byte) int
func stateTr(s *scanner, c byte) int
func stateTru(s *scanner, c byte) int
tagOptions is the string following a comma in a struct field's "json"
tag, or the empty string. It does not include the leading comma. Contains reports whether a comma-separated list of options
contains a particular substr flag. substr must be surrounded by a
string boundary or commas.
func parseTag(tag string) (string, tagOptions)
Package-Level Functions (total 89, in which 9 are exported)
Compact appends to dst the JSON-encoded src with
insignificant space characters elided.
HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029
characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029
so that the JSON will be safe to embed inside HTML <script> tags.
For historical reasons, web browsers don't honor standard HTML
escaping within <script> tags, so an alternative JSON encoding must be used.
Indent appends to dst an indented form of the JSON-encoded src.
Each element in a JSON object or array begins on a new,
indented line beginning with prefix followed by one or more
copies of indent according to the indentation nesting.
The data appended to dst does not begin with the prefix nor
any indentation, to make it easier to embed inside other formatted JSON data.
Although leading space characters (space, tab, carriage return, newline)
at the beginning of src are dropped, trailing space characters
at the end of src are preserved and copied to dst.
For example, if src has no trailing spaces, neither will dst;
if src ends in a trailing newline, so will dst.
Marshal returns the JSON encoding of v.
Marshal traverses the value v recursively.
If an encountered value implements the Marshaler interface
and is not a nil pointer, Marshal calls its MarshalJSON method
to produce JSON. If no MarshalJSON method is present but the
value implements encoding.TextMarshaler instead, Marshal calls
its MarshalText method and encodes the result as a JSON string.
The nil pointer exception is not strictly necessary
but mimics a similar, necessary exception in the behavior of
UnmarshalJSON.
Otherwise, Marshal uses the following type-dependent default encodings:
Boolean values encode as JSON booleans.
Floating point, integer, and Number values encode as JSON numbers.
NaN and +/-Inf values will return an [UnsupportedValueError].
String values encode as JSON strings coerced to valid UTF-8,
replacing invalid bytes with the Unicode replacement rune.
So that the JSON will be safe to embed inside HTML <script> tags,
the string is encoded using HTMLEscape,
which replaces "<", ">", "&", U+2028, and U+2029 are escaped
to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029".
This replacement can be disabled when using an Encoder,
by calling SetEscapeHTML(false).
Array and slice values encode as JSON arrays, except that
[]byte encodes as a base64-encoded string, and a nil slice
encodes as the null JSON value.
Struct values encode as JSON objects.
Each exported struct field becomes a member of the object, using the
field name as the object key, unless the field is omitted for one of the
reasons given below.
The encoding of each struct field can be customized by the format string
stored under the "json" key in the struct field's tag.
The format string gives the name of the field, possibly followed by a
comma-separated list of options. The name may be empty in order to
specify options without overriding the default field name.
The "omitempty" option specifies that the field should be omitted
from the encoding if the field has an empty value, defined as
false, 0, a nil pointer, a nil interface value, and any empty array,
slice, map, or string.
As a special case, if the field tag is "-", the field is always omitted.
Note that a field with name "-" can still be generated using the tag "-,".
Examples of struct field tags and their meanings:
// Field appears in JSON as key "myName".
Field int `json:"myName"`
// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`
// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`
// Field is ignored by this package.
Field int `json:"-"`
// Field appears in JSON as key "-".
Field int `json:"-,"`
The "string" option signals that a field is stored as JSON inside a
JSON-encoded string. It applies only to fields of string, floating point,
integer, or boolean types. This extra level of encoding is sometimes used
when communicating with JavaScript programs:
Int64String int64 `json:",string"`
The key name will be used if it's a non-empty string consisting of
only Unicode letters, digits, and ASCII punctuation except quotation
marks, backslash, and comma.
Anonymous struct fields are usually marshaled as if their inner exported fields
were fields in the outer struct, subject to the usual Go visibility rules amended
as described in the next paragraph.
An anonymous struct field with a name given in its JSON tag is treated as
having that name, rather than being anonymous.
An anonymous struct field of interface type is treated the same as having
that type as its name, rather than being anonymous.
The Go visibility rules for struct fields are amended for JSON when
deciding which field to marshal or unmarshal. If there are
multiple fields at the same level, and that level is the least
nested (and would therefore be the nesting level selected by the
usual Go rules), the following extra rules apply:
1) Of those fields, if any are JSON-tagged, only tagged fields are considered,
even if there are multiple untagged fields that would otherwise conflict.
2) If there is exactly one field (tagged or not according to the first rule), that is selected.
3) Otherwise there are multiple fields, and all are ignored; no error occurs.
Handling of anonymous struct fields is new in Go 1.1.
Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of
an anonymous struct field in both current and earlier versions, give the field
a JSON tag of "-".
Map values encode as JSON objects. The map's key type must either be a
string, an integer type, or implement encoding.TextMarshaler. The map keys
are sorted and used as JSON object keys by applying the following rules,
subject to the UTF-8 coercion described for string values above:
- keys of any string type are used directly
- encoding.TextMarshalers are marshaled
- integer keys are converted to strings
Pointer values encode as the value pointed to.
A nil pointer encodes as the null JSON value.
Interface values encode as the value contained in the interface.
A nil interface value encodes as the null JSON value.
Channel, complex, and function values cannot be encoded in JSON.
Attempting to encode such a value causes Marshal to return
an UnsupportedTypeError.
JSON cannot represent cyclic data structures and Marshal does not
handle them. Passing cyclic structures to Marshal will result in
an error.
MarshalIndent is like Marshal but applies Indent to format the output.
Each JSON element in the output will begin on a new line beginning with prefix
followed by one or more copies of indent according to the indentation nesting.
NewDecoder returns a new decoder that reads from r.
The decoder introduces its own buffering and may
read data from r beyond the JSON values requested.
NewEncoder returns a new encoder that writes to w.
Unmarshal parses the JSON-encoded data and stores the result
in the value pointed to by v. If v is nil or not a pointer,
Unmarshal returns an InvalidUnmarshalError.
Unmarshal uses the inverse of the encodings that
Marshal uses, allocating maps, slices, and pointers as necessary,
with the following additional rules:
To unmarshal JSON into a pointer, Unmarshal first handles the case of
the JSON being the JSON literal null. In that case, Unmarshal sets
the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into
the value pointed at by the pointer. If the pointer is nil, Unmarshal
allocates a new value for it to point to.
To unmarshal JSON into a value implementing the Unmarshaler interface,
Unmarshal calls that value's UnmarshalJSON method, including
when the input is a JSON null.
Otherwise, if the value implements encoding.TextUnmarshaler
and the input is a JSON quoted string, Unmarshal calls that value's
UnmarshalText method with the unquoted form of the string.
To unmarshal JSON into a struct, Unmarshal matches incoming object
keys to the keys used by Marshal (either the struct field name or its tag),
preferring an exact match but also accepting a case-insensitive match. By
default, object keys which don't have a corresponding struct field are
ignored (see Decoder.DisallowUnknownFields for an alternative).
To unmarshal JSON into an interface value,
Unmarshal stores one of these in the interface value:
bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null
To unmarshal a JSON array into a slice, Unmarshal resets the slice length
to zero and then appends each element to the slice.
As a special case, to unmarshal an empty JSON array into a slice,
Unmarshal replaces the slice with a new empty slice.
To unmarshal a JSON array into a Go array, Unmarshal decodes
JSON array elements into corresponding Go array elements.
If the Go array is smaller than the JSON array,
the additional JSON array elements are discarded.
If the JSON array is smaller than the Go array,
the additional Go array elements are set to zero values.
To unmarshal a JSON object into a map, Unmarshal first establishes a map to
use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal
reuses the existing map, keeping existing entries. Unmarshal then stores
key-value pairs from the JSON object into the map. The map's key type must
either be any string type, an integer, implement json.Unmarshaler, or
implement encoding.TextUnmarshaler.
If the JSON-encoded data contain a syntax error, Unmarshal returns a SyntaxError.
If a JSON value is not appropriate for a given target type,
or if a JSON number overflows the target type, Unmarshal
skips that field and completes the unmarshaling as best it can.
If no more serious errors are encountered, Unmarshal returns
an UnmarshalTypeError describing the earliest such error. In any
case, it's not guaranteed that all the remaining fields following
the problematic one will be unmarshaled into the target object.
The JSON null value unmarshals into an interface, map, pointer, or slice
by setting that Go value to nil. Because null is often used in JSON to mean
“not present,” unmarshaling a JSON null into any other Go type has no effect
on the value and produces no error.
When unmarshaling quoted strings, invalid UTF-8 or
invalid UTF-16 surrogate pairs are not treated as an error.
Instead, they are replaced by the Unicode replacement
character U+FFFD.
Valid reports whether data is a valid JSON encoding.
cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
checkValid verifies that data is valid JSON-encoded data.
scan is passed in for use by checkValid to avoid an allocation.
checkValid returns nil or a SyntaxError.
dominantField looks through the fields, all of which are known to
have the same name, to find the single field that dominates the
others using Go's embedding rules, modified by the presence of
JSON tags. If there are multiple top-level fields, the boolean
will be false: This condition is an error in Go and we skip all
the fields.
getu4 decodes \uXXXX from the beginning of s, returning the hex value,
or it returns -1.
indirect walks down v allocating pointers as needed,
until it gets to a non-pointer.
If it encounters an Unmarshaler, indirect stops and returns that.
If decodingNull is true, indirect stops at the first settable pointer so it
can be set to nil.
parseTag splits a struct field's json tag into its name and
comma-separated options.
quoteChar formats c as a quoted character literal.
state0 is the state after reading `0` during a number.
state1 is the state after reading a non-zero integer during a number,
such as after reading `1` or `100` but not `0`.
stateBeginString is the state after reading `{"key": value,`.
stateBeginStringOrEmpty is the state after reading `{`.
stateBeginValue is the state at the beginning of the input.
stateBeginValueOrEmpty is the state after reading `[`.
stateDot is the state after reading the integer and decimal point in a number,
such as after reading `1.`.
stateDot0 is the state after reading the integer, decimal point, and subsequent
digits of a number, such as after reading `3.14`.
stateE is the state after reading the mantissa and e in a number,
such as after reading `314e` or `0.314e`.
stateE0 is the state after reading the mantissa, e, optional sign,
and at least one digit of the exponent in a number,
such as after reading `314e-2` or `0.314e+1` or `3.14e0`.
stateEndTop is the state after finishing the top-level value,
such as after reading `{}` or `[1,2,3]`.
Only space characters should be seen now.
stateEndValue is the state after completing a value,
such as after reading `{}` or `true` or `["x"`.
stateError is the state after reaching a syntax error,
such as after reading `[1}` or `5.1.2`.
stateESign is the state after reading the mantissa, e, and sign in a number,
such as after reading `314e-` or `0.314e+`.
stateF is the state after reading `f`.
stateFa is the state after reading `fa`.
stateFal is the state after reading `fal`.
stateFals is the state after reading `fals`.
stateInString is the state after reading `"`.
stateInStringEsc is the state after reading `"\` during a quoted string.
stateInStringEscU is the state after reading `"\u` during a quoted string.
stateInStringEscU1 is the state after reading `"\u1` during a quoted string.
stateInStringEscU12 is the state after reading `"\u12` during a quoted string.
stateInStringEscU123 is the state after reading `"\u123` during a quoted string.
stateN is the state after reading `n`.
stateNeg is the state after reading `-` during a number.
typeFields returns a list of fields that JSON should recognize for the given type.
The algorithm is breadth-first search over the set of structs to include - the top struct
and then any reachable anonymous structs.
htmlSafeSet holds the value true if the ASCII character with the given
array position can be safely represented inside a JSON string, embedded
inside of HTML <script> tags, without any additional escaping.
All values are true except for the ASCII control characters (0-31), the
double quote ("), the backslash character ("\"), HTML opening and closing
tags ("<" and ">"), and the ampersand ("&").
safeSet holds the value true if the ASCII character with the given array
position can be represented inside a JSON string without any further
escaping.
All values are true except for the ASCII control characters (0-31), the
double quote ("), and the backslash character ("\").
Package-Level Constants (total 28, none are exported)
indentGrowthFactor specifies the growth factor of indenting JSON input.
Empirically, the growth factor was measured to be between 1.4x to 1.8x
for some set of compacted JSON with the indent being a single tab.
Specify a growth factor slightly larger than what is observed
to reduce probability of allocation in appendIndent.
A factor no higher than 2 ensures that wasted space never exceeds 50%.
This limits the max nesting depth to prevent stack overflow.
This is permitted by https://tools.ietf.org/html/rfc7159#section-9
These values are stored in the parseState stack.
They give the current state of a composite value
being scanned. If the parser is inside a nested value
the parseState describes the nested state, outermost at entry 0.
These values are stored in the parseState stack.
They give the current state of a composite value
being scanned. If the parser is inside a nested value
the parseState describes the nested state, outermost at entry 0.
These values are stored in the parseState stack.
They give the current state of a composite value
being scanned. If the parser is inside a nested value
the parseState describes the nested state, outermost at entry 0.
phasePanicMsg is used as a panic message when we end up with something that
shouldn't happen. It can indicate a bug in the JSON decoder, or that
something is editing the data slice while the decoder executes.
These values are returned by the state transition functions
assigned to scanner.state and the method scanner.eof.
They give details about the current state of the scan that
callers might be interested to know about.
It is okay to ignore the return value of any particular
call to scanner.state: if one call returns scanError,
every subsequent call will return scanError too.
These values are returned by the state transition functions
assigned to scanner.state and the method scanner.eof.
They give details about the current state of the scan that
callers might be interested to know about.
It is okay to ignore the return value of any particular
call to scanner.state: if one call returns scanError,
every subsequent call will return scanError too.
These values are returned by the state transition functions
assigned to scanner.state and the method scanner.eof.
They give details about the current state of the scan that
callers might be interested to know about.
It is okay to ignore the return value of any particular
call to scanner.state: if one call returns scanError,
every subsequent call will return scanError too.
These values are returned by the state transition functions
assigned to scanner.state and the method scanner.eof.
They give details about the current state of the scan that
callers might be interested to know about.
It is okay to ignore the return value of any particular
call to scanner.state: if one call returns scanError,
every subsequent call will return scanError too.
Continue.
Stop.
These values are returned by the state transition functions
assigned to scanner.state and the method scanner.eof.
They give details about the current state of the scan that
callers might be interested to know about.
It is okay to ignore the return value of any particular
call to scanner.state: if one call returns scanError,
every subsequent call will return scanError too.
These values are returned by the state transition functions
assigned to scanner.state and the method scanner.eof.
They give details about the current state of the scan that
callers might be interested to know about.
It is okay to ignore the return value of any particular
call to scanner.state: if one call returns scanError,
every subsequent call will return scanError too.
These values are returned by the state transition functions
assigned to scanner.state and the method scanner.eof.
They give details about the current state of the scan that
callers might be interested to know about.
It is okay to ignore the return value of any particular
call to scanner.state: if one call returns scanError,
every subsequent call will return scanError too.
These values are returned by the state transition functions
assigned to scanner.state and the method scanner.eof.
They give details about the current state of the scan that
callers might be interested to know about.
It is okay to ignore the return value of any particular
call to scanner.state: if one call returns scanError,
every subsequent call will return scanError too.
These values are returned by the state transition functions
assigned to scanner.state and the method scanner.eof.
They give details about the current state of the scan that
callers might be interested to know about.
It is okay to ignore the return value of any particular
call to scanner.state: if one call returns scanError,
every subsequent call will return scanError too.
These values are returned by the state transition functions
assigned to scanner.state and the method scanner.eof.
They give details about the current state of the scan that
callers might be interested to know about.
It is okay to ignore the return value of any particular
call to scanner.state: if one call returns scanError,
every subsequent call will return scanError too.
The pages are generated with Goldsv0.6.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.