Customizing JSON Parsing Defaults in Go
When parsing JSON in Go, assigning default values to fields that are not present can enhance data manipulation. Here's how you can achieve this using the encoding/json package or leverage an external Go library.
Using encoding/json
The encoding/json package offers a straightforward solution. Instead of passing an empty struct to json.Unmarshal, you can initialize it with default values. For example:
type Test struct { A string "a" B string "b" C string } example := []byte(`{"A": "1", "C": "3"}`) out := Test{} err := json.Unmarshal(example, &out) if err != nil { panic(err) } fmt.Printf("%+v", out)
Utilizing External Libraries
If the encoding/json package doesn't fully meet your needs, there are external Go libraries that provide enhanced JSON parsing functionality. One popular option is the go-json library, which allows you to specify default values for missing fields using struct tags.
import ( "encoding/json" "github.com/go-json" ) type Test struct { A string `json:"a,omitempty"` B string `json:"b,omitempty"` C string `json:"c,omitempty"` } example := []byte(`{"A": "1", "C": "3"}`) out := Test{ DefaultA: "a", DefaultB: "b", DefaultC: "c", } err := json.Unmarshal(example, &out) if err != nil { panic(err) } fmt.Printf("%+v", out)
The above is the detailed content of How Can I Set Default Values for Missing JSON Fields in Go?. For more information, please follow other related articles on the PHP Chinese website!