Home > Backend Development > Golang > Why are my Go struct fields empty when parsing JSON?

Why are my Go struct fields empty when parsing JSON?

Barbara Streisand
Release: 2024-11-12 10:27:02
Original
841 people have browsed it

Why are my Go struct fields empty when parsing JSON?

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template