version: 1.10
package json
import "encoding/json"
Overview
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.html
package json_test
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 Example_customMarshalJSON() {
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])
// Output:
// Zoo Census:
// * Gophers: 3
// * Zebras: 2
// * Unknown: 3
}
Index
- func Compact(dst *bytes.Buffer, src []byte) error
- func HTMLEscape(dst *bytes.Buffer, src []byte)
- func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error
- func Marshal(v interface{}) ([]byte, error)
- func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
- func Unmarshal(data []byte, v interface{}) error
- func Valid(data []byte) bool
- type Decoder
- type Delim
- type Encoder
- type InvalidUTF8Error
- type InvalidUnmarshalError
- type Marshaler
- type MarshalerError
- type Number
- type RawMessage
- type SyntaxError
- type Token
- type UnmarshalFieldError
- type UnmarshalTypeError
- type Unmarshaler
- type UnsupportedTypeError
- type UnsupportedValueError
Examples
- Decoder
- Decoder.Decode (Stream)
- Decoder.Token
- Indent
- Marshal
- MarshalIndent
- RawMessage (Marshal)
- RawMessage (Unmarshal)
- Unmarshal
- Package (CustomMarshalJSON)
Package files
decode.go encode.go fold.go indent.go scanner.go stream.go tables.go tags.go
func Compact ¶
func Compact(dst *bytes.Buffer, src []byte) error
Compact appends to dst the JSON-encoded src with insignificant space characters elided.
func HTMLEscape ¶
func HTMLEscape(dst *bytes.Buffer, src []byte)
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