Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if JSON file has field

Tags:

go

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!"
}
like image 845
tommyd456 Avatar asked Aug 13 '15 13:08

tommyd456


People also ask

How do you check if a JSON object contains a key or not?

Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().

How do I check if a JSON string is valid?

To check if a string is JSON in JavaScript, we can use the JSON. parse method within a try-catch block. to check if jsonStr is a valid JSON string. Since we created the JSON string by calling JSON.

How do I know if JSON format is correct?

The best way to find and correct errors while simultaneously saving time is to use an online tool such as JSONLint. JSONLint will check the validity of your JSON code, detect and point out line numbers of the code containing errors.


1 Answers

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

like image 192
Bayta Darell Avatar answered Oct 17 '22 15:10

Bayta Darell