Golang Json处理 | KaiQ.Gu|KerwinKoo Blog

JerryXia 发表于 , 阅读 (0)

golang 将struct内容生成Json

引用json包

1
import “encoding/json”

结构体定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
type Config struct {
Addr string `json:"address"`
BaseURL string `json:"base_url"`
BasePath string `json:"base_path"`

Username string `json:"username"`
Password string `json:"password"`

HomeArticles int `json:"home_articles"`
Title string `json:"title"`
Footer string `json:"footer"`
DocURLFormat string `json:"doc_url_format"`

ContentPath string `json:"content_path"`
UploadPath string `json:"upload_path"`
TemplatePath string `json:"template_path"`

PublicPath string `json:"public_path"` // all parsed html/content etc...
Favicon string `json:"favicon"`
LinkFiles []string `json:"link_files"`

TLSCertFile string `json:"certfile"`
TLSKeyFile string `json:"keyfile"`
}

结构体变量赋值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
cfg := &bla.Config{
Addr: ":8080",

BaseURL: "http://localhost:8080",
BasePath: "/",

Username: "admin",

Password: "",

HomeArticles: 10,

Title: "Some blah",
Footer: "My daily blog",
DocURLFormat: "%s",

ContentPath: DefaultContent,

UploadPath: "./bla_uploads",
TemplatePath: "./bla_default_template",

PublicPath: "./bla_public",

Favicon: "",
LinkFiles: []string{},

TLSCertFile: "",

TLSKeyFile: "",
}

生成Json文件

1
2
3
4
5
6
7
8
9
10
11
f, err := os.Create("bla.config.json")
if err != nil {
log.Fatal(err)
}
defer f.Close()
b, err := json.MarshalIndent(cfg, " ", " ")
if err != nil {
log.Fatal(err)
}
f.Write(b)
log.Printf("new config :\n%s", b)

// b, err := json.Marshal(cfg)说明:

    1. b, err := json.Marshal(cfg) 生成的json文件可读性差,没有缩进。
    1. b, err := json.MarshalIndent(cfg, " ", " ") 生成的Json文件包含缩进,函数原形是func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error),第一个参数为包含Json内容的结构体,参数prefix为前缀缩进(冒号之后的),参数indent为整个参数的缩进。