2

I'm new to Go. I was trying to fetch and marshal json data to a struct. My sample data looks like this:

var reducedFieldData = []byte(`[
    {"model":"Traverse","vin":"1gnkrhkd6ej111234"}
    ,{"model":"TL","vin":"19uua66265a041234"}
]`)

If I define the struct for receiving the data like this:

type Vehicle struct {
    Model string
    Vin   string
}

The call to Unmarshal works as expected. However, if I use lower case for the fields ("model" and "vin") which actually matches cases for the field names in the data it will return empty strings for the values.

Is this expected behavior? Can the convention be turned off?

jrf
  • 41
  • 4
  • 3
    Possible duplicate of [My structures are not marshalling into json](https://stackoverflow.com/questions/15452004/my-structures-are-not-marshalling-into-json) – RickyA Jul 25 '17 at 20:57

1 Answers1

4

Fields need to be exported (declared with an uppercase first letter) or the reflection library cannot edit them. Since the JSON (un)marshaller uses reflection, it cannot read or write unexported fields.

So yes, it is expected, and no, you cannot change it. Sorry.

You can add tags to a field to change the name the marshaller uses:

Model string `json:"model"`

See the documentation for more info on the field tags "encoding/json" supports.

Milo Christiansen
  • 3,204
  • 2
  • 23
  • 36
  • Thanks for the answer. What happens if you attempt to Unmarshal a document that contains both "model" and "Model"? Clearly, you wouldn't want to define this, but we're not always in control of how data sources are defined :) – jrf Jul 25 '17 at 20:59
  • Then field "Model" will not be stored anywhere AFAIK. You could add two fields (with appropriate tags) to your struct, but that would be messy. The library assumes that field names will be case sensitive, and there isn't an easy way to avoid that. If you really must handle both, see [this part of the documentation](https://golang.org/pkg/encoding/json/#Unmarshaler) for what you need. – Milo Christiansen Jul 25 '17 at 21:09