Home >Backend Development >Golang >How to Specify Default Values When Parsing JSON in Go?
Specifying Default Values in JSON Parsing with Go
When parsing JSON data into a Go struct, it is often desirable to specify default values for fields that are not present in the JSON. The built-in encoding/json package provides a straightforward mechanism to achieve this.
When calling json.Unmarshal, instead of providing an empty struct, you can provide one with default values. Fields not present in the JSON will retain their default values after unmarshalling.
For example, consider the following struct:
type Test struct { A string B string C string }
With default values of "a", "b", and "c" for A, B, and C respectively, parsing the JSON below would return a struct with the specified default values:
{"A": "1", "C": "3"}
var example []byte = []byte(`{"A": "1", "C": "3"}`) out := Test{ A: "default a", B: "default b", // default for C will be "", the empty value for a string } err := json.Unmarshal(example, &out) if err != nil { panic(err) } fmt.Printf("%+v", out)
This code would output:
{A:1 B:default b C:3}
As demonstrated, json.Unmarshal overwrites values specified in the JSON, while leaving unspecified fields with their default values. This technique provides a convenient way to handle missing or incomplete JSON data when parsing into structs.
The above is the detailed content of How to Specify Default Values When Parsing JSON in Go?. For more information, please follow other related articles on the PHP Chinese website!