检测JSON文件是否具有字段

huangapple go评论66阅读模式
英文:

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

playground示例

英文:

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.

playground example

huangapple
  • 本文由 发表于 2015年8月13日 21:25:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/31989595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定