Parsing JSON with Default Values in Go
When parsing JSON in Go and encountering missing or undefined fields, it's often desirable to assign default values to ensure a complete and consistent data representation.
To achieve this using the built-in encoding/json package, avoid passing an empty struct to json.Unmarshal. Instead, initialize the struct with default values. For instance, let's consider the following struct:
type Test struct { A string B string C string }
With default values of "a", "b", and "c" for fields A, B, and C, respectively, we can parse the JSON string:
{"A": "1", "C": 3}
into the following struct:
out := Test{ A: "default a", B: "default b", // C defaults to the empty value "" }
By calling json.Unmarshal(example, &out), the JSON is unmarshaled into out, overriding specified fields with their values from the JSON while preserving default values for the remaining fields. The above example would result in {A:1 B:default b C:3}.
This technique offers a straightforward way to handle missing fields in JSON data parsing while maintaining data integrity.
The above is the detailed content of How to Handle Missing JSON Fields with Default Values in Go?. For more information, please follow other related articles on the PHP Chinese website!