gpt4 book ai didi

go - 检测 JSON 文件是否有字段

转载 作者:IT王子 更新时间:2023-10-29 01:23:14 27 4
gpt4 key购买 nike

我的应用程序从配置文件中读取设置:

file, _ := os.Open("config.json")
config := config.Config{}
err := json.NewDecoder(file).Decode(&config)
if err != nil {
//handle err
}

我的 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 (Email field found in JSON file) {
output "You want to receive emails"
} else {
output "No emails for you!"
}

最佳答案

Config 更改为

type Config struct {
Site Site
Email *Email
}

使用 c.Email != nil 测试 JSON 文件中是否将电子邮件指定为字符串值。如果 c.Email == nil,则未指定电子邮件或 null

playground example

关于go - 检测 JSON 文件是否有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31989595/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com