I'm decoding some JSON into a struct, and I'd like to handle the case where a particular field is not provided.
Struct:
type Config struct {
SolrHost string
SolrPort int
SolrCore string
Servers map[string][]int
}
JSON to decode:
{
"solrHost": "localhost",
"solrPort": 8380,
"solrCore": "testcore",
}
In the method that decodes the JSON, I'd like to check if the map[string][]int
has been initialised, and if not, do so.
Current code:
func decodeJson(input string, output *Config) error {
if len(input) == 0 {
return fmt.Errorf("empty string")
}
decoder := json.NewDecoder(strings.NewReader(input))
err := decoder.Decode(output)
if err != nil {
if err != io.EOF {
return err
}
}
// if output.Server.isNotInitialized...
return nil
}
Could I make use of recover()
? Is that the "nicest" way to achieve my task?
Initializing map using map literals: Map literal is the easiest way to initialize a map with data just simply separate the key-value pair with a colon and the last trailing colon is necessary if you do not use, then the compiler will give an error.
You can use len : if len(m) == 0 { .... }
Go by Example: Maps To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt. Println will show all of its key/value pairs.
Check if Key is Present in Map in Golang To check if specific key is present in a given map in Go programming, access the value for the key in map using map[key] expression. This expression returns the value if present, and a boolean value representing if the key is present or not.
The zero value of any map is nil
, so just check against it:
if output.Servers == nil { /* ... */ }
Alternatively, you can also check its length. This also handles the case of empty map:
if len(output.Servers) == 0 { /* ... */ }
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