Tuesday, May 28, 2013

Unmarshaling JSON using Go

I had a Doh! moment today writing some code to Unmarshal JSON string into a Go object. I swore up and down I had the code right, but my Object just didn't get populated. I was searching around and was about to break down and post to ask for help when it finally clicked.

I used lower case names for the fields in my structure, effectively rendering them private! So, once I went through and made the fields all start with a Capital, making them public, I was able to populate the structure.

For example:

type Some struct {
  name string `json:"Name of item"`
  age int `json:"age"`
}

Is a valid structure, but you won't populate using

some := Some{}
data, err = json.UnMarshal(jsonBytes, &some)

If you check some.name - it will be empty because it's lower case. The correct struct is:

type Some struct {
  Name string `json:"Name of item"`
  Age int `json:"age"`
}