检测JSON文件是否具有字段

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

Detect if JSON file has field

问题

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

  1. file, _ := os.Open("config.json")
  2. config := config.Config{}
  3. err := json.NewDecoder(file).Decode(&config)
  4. if err != nil {
  5. //处理错误
  6. }

我的JSON配置文件大致如下:

  1. {
  2. "site" : {
  3. "url" : "https://example.com"
  4. },
  5. "email" : {
  6. "key" : "abcde"
  7. }
  8. }

我的结构体如下:

  1. type Site struct {
  2. Url string
  3. }
  4. type Email struct {
  5. Key string
  6. }
  7. type Config struct {
  8. Site Site
  9. Email Email
  10. }

我想要有一个选项,可以从JSON文件中删除email字段,以表示不使用电子邮件帐户,所以:

  1. {
  2. "site" : {
  3. "url" : "https://example.com"
  4. }
  5. }

在Go中,如何检测JSON文件中是否存在特定字段,类似于以下代码:

  1. if (在JSON文件中找到Email字段) {
  2. 输出 "您想要接收电子邮件"
  3. } else {
  4. 输出 "您不会收到电子邮件"
  5. }
英文:

My app reads settings from a config file:

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

My JSON config file looks something like this:

  1. {
  2. "site" : {
  3. "url" : "https://example.com"
  4. },
  5. "email" : {
  6. "key" : "abcde"
  7. }
  8. }

My structs are:

  1. type Site struct {
  2. Url string
  3. }
  4. type Email struct {
  5. Key string
  6. }
  7. type Config struct {
  8. Site Site
  9. Email Email
  10. }

I would like the option of removing the email field from the JSON file to indicate that no email account will be used so:

  1. {
  2. "site" : {
  3. "url" : "https://example.com"
  4. }
  5. }

How do I detect if a specific field exists in the JSON file in Go so something on the lines of:

  1. if (Email field found in JSON file) {
  2. output "You want to receive emails"
  3. } else {
  4. output "No emails for you!"
  5. }

答案1

得分: 24

Config更改为

  1. type Config struct {
  2. Site Site
  3. Email *Email
  4. }

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

playground示例

英文:

Change Config to

  1. type Config struct {
  2. Site Site
  3. Email *Email
  4. }

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:

确定