Go Reference ยท Encoding and Data Formats
The Go encoding/json package
Overview of Go's encoding/json package: Marshal, Unmarshal, Encoder, Decoder, struct tags, RawMessage, Indent, Valid, custom marshalers and error types.
encoding/json converts Go values to JSON text and back. json.Marshal turns a value into bytes, json.Unmarshal fills a value from bytes, and json.NewEncoder / json.NewDecoder do the same on streams such as files and HTTP bodies.
Struct fields are matched to JSON object keys by name or by a struct tag. Only exported fields take part. Types can take over their own encoding by implementing json.Marshaler / json.Unmarshaler (or encoding.TextMarshaler).
b, _ := json.Marshal(map[string]int{"a": 1}) fmt.Println(string(b)) // {"a":1}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Marshal(v any) ([]byte, error) func MarshalIndent(v any, prefix, indent string) ([]byte, error) func Unmarshal(data []byte, v any) error func Valid(data []byte) bool func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error func Compact(dst *bytes.Buffer, src []byte) error func HTMLEscape(dst *bytes.Buffer, src []byte) func NewEncoder(w io.Writer) *Encoder func NewDecoder(r io.Reader) *Decoder type Marshaler interface { MarshalJSON() ([]byte, error) } type Unmarshaler interface { UnmarshalJSON([]byte) error } type RawMessage []byte type Number string
| Name | Description |
|---|---|
Marshal, MarshalIndent |
Value to JSON bytes (compact or indented). |
Unmarshal |
JSON bytes into a pointer to a value. |
Encoder, Decoder |
Streaming API: many values, SetIndent, DisallowUnknownFields, UseNumber, More, Token. |
RawMessage |
Bytes kept undecoded until you need them. |
Number |
Exact numeric text, produced by Decoder.UseNumber. |
Valid, Indent, Compact, HTMLEscape |
Helpers working on JSON text. |
| Errors | *SyntaxError, *UnmarshalTypeError, *InvalidUnmarshalError, *UnsupportedTypeError, *UnsupportedValueError, *MarshalerError. |
Usage notes
- Type mapping:
bool, strings, numbers,nilpointers/interfaces/maps/slices (null), slices and arrays ([...]), maps with string, integer orTextMarshalerkeys ({...}), structs ({...}).[]bytebecomes a base64 string. Channels, functions and complex numbers cannot be encoded. - Map keys are sorted on output, so
Marshalof a map is deterministic. - Case-insensitive matching: on decoding, a key matches a field name ignoring case if there is no exact tag match. Unknown keys are ignored unless you call
DisallowUnknownFields. - Numbers into
anybecomefloat64, losing precision above 2^53. UseUseNumber, a typed field, orjson.Number. time.Timeencodes as an RFC 3339 string,time.Durationas an integer of nanoseconds, anderrorvalues as{}(they have no exported fields).- Unmarshal needs a pointer. Passing a value returns an
*InvalidUnmarshalError. - Performance: reflection-based and allocation-heavy. For hot paths cache decoded structs, stream with
Decoder, or consider generated code. Go 1.25 added an experimental fasterencoding/json/v2(build tagGOEXPERIMENT=jsonv2); the stable API here is unchanged. - Security: limit body sizes (
http.MaxBytesReader) before decoding untrusted input.