Zac Gross

Code & More

Lowercase JSON Fields With Golang

| Comments

The base GO libraries provide a handy function for marshaling structs into JSON. I recently came across an issue when writing webservices in GO for an existing javascript client. The problem was the client expected the JSON data to have field names starting with lowercase letters. GO’s naming convention is obviously going to make all struct fields uppercase by default as they need to be exported. I ended up copying the JSON marshaler code from GO’s library and modifiying it with a new paramater that will lowercase JSON field names when set. Because GO isn’t on github and I am strapped for time I just copied the code into a new util namespace and made the modifications as a couple of other gophers in #go-nuts were interested in using it.

Usage is simple, when the 2nd paramater is set to true, all fieldnames will start with a lowercase letter(other capitalization remains unchanged):

b, err = jsonutils.Marshal(<some obj>, <lowercase fieldnames:true/false>)

The source code can be downloaded from github:

And here is some boilerplate code to use it in a Revel controller: