Parsing JSON into a Struct in Go
While attempting to parse JSON into a Go struct, you encounter an unexpected output: empty struct values and a false boolean value. By default, struct fields must be exported (begin with uppercase letters) to be recognized by the encoder/decoder. Here's a revised version of your code:
// Define your struct with exported fields type Settings struct { ServerMode bool `json:"serverMode"` SourceDir string `json:"sourceDir"` TargetDir string `json:"targetDir"` } func main() { // Open the config file configFile, err := os.Open("config.json") if err != nil { printError("opening config file", err.Error()) } jsonParser := json.NewDecoder(configFile) settings := Settings{} // Initialize the struct // Decode the JSON if err = jsonParser.Decode(&settings); err != nil { printError("parsing config file", err.Error()) } fmt.Printf("%v %s %s", settings.ServerMode, settings.SourceDir, settings.TargetDir) }
With these modifications, the encoder/decoder can properly access and modify the fields of your struct, resulting in the desired parsed values.
The above is the detailed content of Why are my Go struct fields empty when parsing JSON?. For more information, please follow other related articles on the PHP Chinese website!