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!"
}
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().
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With