-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
61 lines (46 loc) · 1.02 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
56
57
58
59
60
61
package main
import (
"encoding/json"
"fmt"
"os"
)
type ColorGroup struct {
ID int
Name string
Colors []string
}
type Animal struct {
Name string
Order string
}
func main() {
//encode-------------------------
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := json.Marshal(group)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
fmt.Println("")
fmt.Println(string(b))
//decode-----------------------------
var jsonBlob = []byte(`[
{"Name": "Platypus", "Order": "Monotremata"},
{"Name": "Quoll", "Order": "Dasyuromorphia"}
]`)
var animals []Animal
err1 := json.Unmarshal(jsonBlob, &animals)
if err1 != nil {
fmt.Println("error:", err1)
}
fmt.Println(animals)
}
// Encode Output:
// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
// Decode Output:
// [{Platypus Monotremata} {Quoll Dasyuromorphia}]