-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path47_json.go
More file actions
104 lines (85 loc) · 2.99 KB
/
47_json.go
File metadata and controls
104 lines (85 loc) · 2.99 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package gobyexample
import (
"encoding/json"
"fmt"
"os"
)
// Define structs to demonstrate encoding and decoding
// of custom types
type response1 struct {
Page int
Fruits []string
}
type response2 struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}
// JSONDemo - demonstrates JSON encoding and decoding in Go
func JSONDemo() {
// encoding basic types
boolB, _ := json.Marshal(true)
fmt.Println(string(boolB))
intB, _ := json.Marshal(1)
fmt.Println(string(intB))
floatB, _ := json.Marshal(2.34)
fmt.Println(string(floatB))
strB, _ := json.Marshal("gopher")
fmt.Println(string(strB))
// slices and maps encode to JSON arrays and objects as expected
slcD := []string{"apple", "peach", "pear"}
slcB, _ := json.Marshal(slcD)
fmt.Println(string(slcB))
mapD := map[string]int{"apple": 5, "lettuce": 7}
mapB, _ := json.Marshal(mapD)
fmt.Println(string(mapB))
// The JSON package can automatically encode our custom data types.
// It will only include exported fields in the encoded output and
// will by default use those fields' names as the JSON keys.
res1D := &response1{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
res1B, _ := json.Marshal(res1D)
fmt.Println(string(res1B))
// We can use tags on struct field declarations to customize the
// encoded JSON key names. Check the definition of `response2` above
// to see an example of such tags.
res2D := &response2{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))
// Now we look at decoding JSON data into Go values. Here's an example
// for a generic data structure.
byt := []byte(`{"num":6.13, "strs":["a", "b"]}`)
// We need to provide a variable where the JSON package can put the decoded
// data. This `map[string]interface{}` will hold a map of strings to arbitrary
// data types.
var dat map[string]interface{}
// Here's the actual decoding with a check for errors
if err := json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
fmt.Println(dat)
// In order to use the values in the decoded map, we'll need to cast them to their
// appropriate type.
num := dat["num"].(float64)
fmt.Println(num)
// Accessing nested data requires a series of casts.
strs := dat["strs"].([]interface{})
str1 := strs[0].(string)
fmt.Println(str1)
// We can also decode JSON into custom data types. This has the advantages of adding
// additional type-safety to our programs and eliminating the need for type assertions
// when accessing the decoded data.
str := `{"page": 1, "fruits": ["apple", "peach"]}`
res := response2{}
json.Unmarshal([]byte(str), &res)
fmt.Println(res)
fmt.Println(res.Fruits[0])
// In the above examples we always used bytes and strings as intermediates between the
// data and JSON representation on stdout. We can also stream JSON encodings directly to
// `os.Writers` like `os.Stdout` or even HTTP response bodies.
enc := json.NewEncoder(os.Stdout)
d := map[string]int{"apple": 5, "lettuce": 7}
enc.Encode(d)
}