I'm trying to configure my Go program by creating a JSON file and parsing it into a struct:
var settings struct { serverMode bool sourceDir string targetDir string } func main() { // then config file settings configFile, err := os.Open("config.json") if err != nil { printError("opening config file", err.Error()) } jsonParser := json.NewDecoder(configFile) if err = jsonParser.Decode(&settings); err != nil { printError("parsing config file", err.Error()) } fmt.Printf("%v %s %s", settings.serverMode, settings.sourceDir, settings.targetDir) return }
The config.json file:
{ "serverMode": true, "sourceDir": ".", "targetDir": "." }
The Program compiles and runs without any errors, but the print statement outputs:
false
(false and two empty strings)
I've also tried with json.Unmarshal(..)
but had the same result.
How do I parse the JSON in a way that fills the struct values?
json is read with the ioutil. ReadFile() function, which returns a byte slice that is decoded into the struct instance using the json. Unmarshal() function. At last, the struct instance member values are printed using for loop to demonstrate that the JSON file was decoded.
Golang provides multiple APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct.
Reading and Writing JSON Files in GoIt is actually pretty simple to read and write data to and from JSON files using the Go standard library. For writing struct types into a JSON file we have used the WriteFile function from the io/ioutil package. The data content is marshalled/encoded into JSON format.
To unmarshal a JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a special case, to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice with a new empty slice.
You're not exporting your struct elements. They all begin with a lower case letter.
var settings struct { ServerMode bool `json:"serverMode"` SourceDir string `json:"sourceDir"` TargetDir string `json:"targetDir"` }
Make the first letter of your stuct elements upper case to export them. The JSON encoder/decoder wont use struct elements which are not exported.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With