英文:
Detect if JSON file has field
问题
我的应用程序从配置文件中读取设置:
file, _ := os.Open("config.json")
config := config.Config{}
err := json.NewDecoder(file).Decode(&config)
if err != nil {
    //处理错误
}
我的JSON配置文件大致如下:
{
    "site" : {
        "url" : "https://example.com"
    },
    "email" : {
        "key" : "abcde"
    }
}
我的结构体如下:
type Site struct {
    Url  string
}
type Email struct {
    Key  string
}
type Config struct {
    Site   Site
    Email  Email
}
我想要有一个选项,可以从JSON文件中删除email字段,以表示不使用电子邮件帐户,所以:
{
    "site" : {
        "url" : "https://example.com"
    }
}
在Go中,如何检测JSON文件中是否存在特定字段,类似于以下代码:
if (在JSON文件中找到Email字段) {
    输出 "您想要接收电子邮件"
} else {
    输出 "您不会收到电子邮件"
}
英文:
My app reads settings from a config file:
file, _ := os.Open("config.json")
config := config.Config{}
err := json.NewDecoder(file).Decode(&config)
if err != nil {
    //handle err
}
My JSON config file looks something like this:
{
    "site" : {
        "url" : "https://example.com"
    },
    "email" : {
        "key" : "abcde"
    }
}
My structs are:
type Site struct {
    Url  string
}
type Email struct {
    Key  string
}
type Config struct {
    Site   Site
    Email  Email
}
I would like the option of removing the email field from the JSON file to indicate that no email account will be used so:
{
    "site" : {
        "url" : "https://example.com"
    }
}
How do I detect if a specific field exists in the JSON file in Go so something on the lines of:
if (Email field found in JSON file) {
    output "You want to receive emails"
} else {
    output "No emails for you!"
}
答案1
得分: 24
将Config更改为
type Config struct {
  Site   Site
  Email  *Email
}
使用c.Email != nil来测试JSON文件中是否将电子邮件指定为字符串值。如果c.Email == nil,则表示未指定电子邮件或为null。
英文:
Change Config to
type Config struct {
  Site   Site
  Email  *Email
}
Use c.Email != nil to test if email is specified as a string value in the JSON file.  If c.Email == nil, then email is not specified or null.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论