Home >Backend Development >Golang >How Can I Set Default Values When Parsing JSON in Go?
Specifying Default Values in JSON Parsing with Go
When parsing JSON objects in Go, it may be necessary to specify default values for fields that are not provided in the input JSON. Consider a struct type with the following fields:
type Test struct { A string B string C string }
Suppose the desired default values for A, B, and C are "a", "b", and "c", respectively. When parsing the following JSON:
{"A": "1", "C": 3}
the expected struct would be:
Test{A: "1", B: "b", C: "3"}
Using the encoding/json Package
The built-in encoding/json package in Go allows for the specification of default values during JSON parsing. Instead of using an empty struct, provide a struct with the desired default values as follows:
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)
By calling json.Unmarshal(example, &out), the JSON is unmarshaled into the out struct, overwriting the values specified in the JSON. However, the default values for fields not present in the JSON remain unchanged. Running the example returns:
{A:1 B:default b C:3}
Other Go Libraries
If the encoding/json package does not meet specific requirements, there are other Go libraries that provide similar functionality. Consider the following:
The above is the detailed content of How Can I Set Default Values When Parsing JSON in Go?. For more information, please follow other related articles on the PHP Chinese website!