Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Go, why is my JSON decoding not working here? [duplicate]

Tags:

json

go

decoding

I cannot get the standard library's encoding/json package to work for decoding JSON objects. Here's a minimal example:

b := []byte(`{"groups":[{"name":"foo"},{"name":"bar"}]}`)
type Group struct{ name string }
var contents struct {
    groups []Group
}
err := json.Unmarshal(b, &contents)
fmt.Printf("contents = %+v\nerr = %+v\n", contents, err)

This prints:

contents = {groups:[]}
err = nil

But I expect:

contents = {groups:[{name:foo} {name:bar}]}

What am I doing wrong?

like image 903
Stefan Majewsky Avatar asked Sep 13 '15 21:09

Stefan Majewsky


1 Answers

The field names have to start with a capital letter:

type Group struct{ Name string }
var contents struct {
    Groups []Group
}
like image 81
Caleb Avatar answered Sep 20 '22 05:09

Caleb