forked from agtorre/go-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
55 lines (43 loc) · 1.09 KB
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package confformat
import (
"bytes"
"encoding/json"
"fmt"
)
// JSONData is our common data struct
// with JSON struct tags
type JSONData struct {
Name string `json:"name"`
Age int `json:"age"`
}
// ToJSON dumps the JSONData struct to
// a JSON format bytes.Buffer
func (t *JSONData) ToJSON() (*bytes.Buffer, error) {
d, err := json.Marshal(t)
if err != nil {
return nil, err
}
b := bytes.NewBuffer(d)
return b, nil
}
// Decode will decode into JSONData
func (t *JSONData) Decode(data []byte) error {
return json.Unmarshal(data, t)
}
// OtherJSONExamples shows ways to use types
// beyond structs and other useful functions
func OtherJSONExamples() error {
res := make(map[string]string)
err := json.Unmarshal([]byte(`{"key": "value"}`), &res)
if err != nil {
return err
}
fmt.Println("We can unmarshal into a map instead of a struct:", res)
b := bytes.NewReader([]byte(`{"key2": "value2"}`))
decoder := json.NewDecoder(b)
if err := decoder.Decode(&res); err != nil {
return err
}
fmt.Println("we can also use decoders/encoders to work with streams:", res)
return nil
}