-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonmarshal.go
51 lines (41 loc) · 977 Bytes
/
jsonmarshal.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
package main
import(
"os"
"fmt"
"encoding/json"
)
type Person struct {
Name Name
Email [] Email
}
type Name struct {
Family string
Personal string
}
type Email struct {
Kind string
Address string
}
func main() {
//结构体初始化
person := Person {
Name: Name{Family: "newmarch", Personal: "Jan"},
Email: []Email{Email{Kind: "home", Address: "[email protected]"},
Email{Kind: "work", Address: "[email protected]"}
}
}
saveJSON("person.json", person)
}
func saveJSON(fileName string, key interface{}) {
outFile, err := os.Create(fileName)
checkError(err)
encoder := json.NewEncoder(outFile)
err := encoder.Encode(key)
checkError(err)
outFile.Close()
}
func checkError(err error) {
if err != nil {
fmt.Println(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}