Go Walkthrough: encoding/json package

Ben Johnson
Aug 22, 2016 · 11 min read

What is JSON?

{"name": "mary", "friends: ["stu", "becky"], age: 30}

Tradeoffs of using JSON

$ go test -bench=. encoding/json
BenchmarkCodeEncoder-4 106.26 MB/s
BenchmarkCodeDecoder-4 27.76 MB/s

When should you use JSON?

Encoding streams

type Encoder struct {}func NewEncoder(w io.Writer) *Encoderfunc (enc *Encoder) Encode(v interface{}) error
func Marshal(v interface{}) ([]byte, error)

Type inspection

Encoder compilation

type Marshaler interface {
MarshalJSON() ([]byte, error)
}
type TextMarshaler interface {
MarshalText() (text []byte, err error)
}

Per-field options

type User struct {
Name string `json:"name"`
Age int `json:"age,omitempty"`
Zipcode int `json:"zipcode,string"`
}

Recursive processing

Decoding streams

type Decoder struct {}func NewDecoder(r io.Reader) *Decoderfunc (dec *Decoder) Decode(v interface{}) error
func Unmarshal(data []byte, v interface{}) error

Scanning JSON

Lookahead buffers

Decoding tokens

Custom unmarshaling

type Unmarshaler interface {
UnmarshalJSON([]byte) error
}
type TextUnmarshaler interface {
UnmarshalText(text []byte) error
}

Deferred processing

type T struct {
Type string `json:"type"`
Value json.RawMessage `json:"value"`
}
func (t *T) Val() (interface{}, error) {
switch t.Type {
case "foo":
// parse "t.Value" as Foo
case "bar":
// parse "t.Value" as Bar
default:
return nil, errors.New("invalid type")
}
}
type T struct {
Value json.Number
}
...if strings.Contains(t.Value, ".") {
v, err := t.Value.Float64()
// process as a float
} else {
v, err := t.Value.Int64()
// process as an integer
}

Pretty printing

func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error
func (enc *Encoder) SetIndent(prefix, indent string)
func Compact(dst *bytes.Buffer, src []byte) error

Handling errors during encoding/decoding

Alternative implementations

Conclusion

Go Walkthrough

A series of walkthroughs to help you understand the Go standard library better.

Ben Johnson

Written by

Writing databases and distributed systems in Go.

Go Walkthrough

A series of walkthroughs to help you understand the Go standard library better.