Lowercase JSON key names with JSON Marshal in Go

Solution 1:

Have a look at the docs for encoding/json.Marshal. It discusses using struct field tags to determine how the generated json is formatted.

For example:

type T struct {
    FieldA int    `json:"field_a"`
    FieldB string `json:"field_b,omitempty"`
}

This will generate JSON as follows:

{
    "field_a": 1234,
    "field_b": "foobar"
}

Solution 2:

You could make your own struct with the keys that you want to export, and give them the appropriate json tags for lowercase names. Then you can copy the desired struct into yours before encoding it as JSON. Or if you don't want to bother with making a local struct you could probably make a map[string]interface{} and encode that.