我的应用程序从配置文件中读取设置:
file, _ := os.Open("config.json")
config := config.Config{}
err := json.NewDecoder(file).Decode(&config)
if err != nil {
//handle err
}
Run Code Online (Sandbox Code Playgroud)
我的JSON配置文件看起来像这样:
{
"site" : {
"url" : "https://example.com"
},
"email" : {
"key" : "abcde"
}
}
Run Code Online (Sandbox Code Playgroud)
我的结构是:
type Site struct {
Url string
}
type Email struct {
Key string
}
type Config struct {
Site Site
Email Email
}
Run Code Online (Sandbox Code Playgroud)
我想email从JSON文件中删除该字段的选项,以指示不会使用任何电子邮件帐户,因此:
{
"site" : {
"url" : "https://example.com"
}
}
Run Code Online (Sandbox Code Playgroud)
如何检测Go中的JSON文件中是否存在特定字段,以便以下内容:
if (Email field found in JSON file) {
output "You want to receive emails"
} else {
output "No emails for you!"
}
Run Code Online (Sandbox Code Playgroud)
Cer*_*món 14
更改Config到
type Config struct {
Site Site
Email *Email
}
Run Code Online (Sandbox Code Playgroud)
使用c.Email != nil如果邮件被指定为JSON文件中的字符串值来测试.如果c.Email == nil,则未指定电子邮件或null.