Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Parse a JSON file into a struct with Go

Tags:

json

parsing

go

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?

like image 473
Charles Avatar asked May 21 '13 23:05

Charles


People also ask

How do I read and parse JSON files in Golang?

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.

How do I decode JSON in Golang?

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.

Can you write JSON file using Go language?

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.

How does JSON Unmarshal work Golang?

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.


1 Answers

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.

like image 98
Daniel Avatar answered Sep 28 '22 05:09

Daniel