Go offers built-in support for JSON encoding and decoding, including to and from built-in and custom data types.
Encoding Basic Types
Encode basic data types to JSON strings:
bolB, _ := json.Marshal(true)
fmt.Println(string(bolB))
// Output: true
Encoding Collections
Slices and maps encode to JSON arrays and objects:
slcD := []string{"apple", "peach", "pear"}
slcB, _ := json.Marshal(slcD)
fmt.Println(string(slcB))
// Output: ["apple","peach","pear"]
mapD := map[string]int{"apple": 5, "lettuce": 7}
mapB, _ := json.Marshal(mapD)
fmt.Println(string(mapB))
// Output: {"apple":5,"lettuce":7}
Encoding Custom Types
The JSON package automatically encodes custom data types. Only exported fields are included:
type response1 struct {
Page int
Fruits []string
}
res1D := &response1{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
res1B, _ := json.Marshal(res1D)
fmt.Println(string(res1B))
// Output: {"Page":1,"Fruits":["apple","peach","pear"]}
Custom JSON Keys
Use tags on struct field declarations to customize encoded JSON key names:
type response2 struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}
res2D := &response2{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))
// Output: {"page":1,"fruits":["apple","peach","pear"]}
Decoding JSON
Generic Decoding
Decode JSON into a generic data structure:
byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
var dat map[string]interface{}
if err := json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
fmt.Println(dat)
// Output: map[num:6.13 strs:[a b]]
Type Assertions
Convert decoded values to their appropriate types:
num := dat["num"].(float64)
fmt.Println(num)
// Output: 6.13
strs := dat["strs"].([]interface{})
str1 := strs[0].(string)
fmt.Println(str1)
// Output: a
Decoding to Custom Types
Decode JSON into custom data types for added type-safety:
str := `{"page": 1, "fruits": ["apple", "peach"]}`
res := response2{}
json.Unmarshal([]byte(str), &res)
fmt.Println(res)
// Output: {1 [apple peach]}
fmt.Println(res.Fruits[0])
// Output: apple
Streaming JSON
Encoding to Writers
Stream JSON encodings directly to io.Writers:
enc := json.NewEncoder(os.Stdout)
d := map[string]int{"apple": 5, "lettuce": 7}
enc.Encode(d)
// Output: {"apple":5,"lettuce":7}
Decoding from Readers
Stream reads from io.Readers with json.Decoder:
dec := json.NewDecoder(strings.NewReader(str))
res1 := response2{}
dec.Decode(&res1)
fmt.Println(res1)
// Output: {1 [apple peach]}
json:"fieldname" - Custom name
Customize the JSON key name
Skip this field during encoding/decoding
json:"fieldname,omitempty" - Omit empty
Omit field if it has a zero value
json:"fieldname,string" - String encoding
Encode numbers as JSON strings
Key Functions
Marshal
func(v any) ([]byte, error)
Encodes a value to JSON bytes
Unmarshal
func(data []byte, v any) error
Decodes JSON bytes into a value
NewEncoder
func(w io.Writer) *Encoder
Creates an encoder that writes to w
NewDecoder
func(r io.Reader) *Decoder
Creates a decoder that reads from r
Package Reference