Issue with white space in json struct tags

October 19, 2015   

Go requires all exported fields to start with a capitalized letter. But It is not common for JSON where lower case letter keys are preferred. We can solve this problem by using the struct tags for json.

for an example:

type MyStruct struct {
    SomeField string `json:"some_field"`
}

According to Golang spec

A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored.

But be careful when you create json tags. If there is any white space in json tag, struct will not be unMarshaled properly. If you have a struct such as:

type MyStruct struct {
    Foo string `json: "foo"`
}

When you unmarshal a json string to MyStruct type, it will give you zero value (empty string for a string). This is also very difficult to catch.