简体   繁体   中英

Lowercase JSON key names with JSON Marshal in Go

I wish to use the "encoding/json" package to marshal a struct declared in one of the imported packages of my application.

Eg.:

type T struct {
    Foo int
}

Because it is imported, all available (exported) fields in the struct begins with an upper case letter. But I wish to have lower case key names:

out, err := json.Marshal(&T{Foo: 42})

will result in

{"Foo":42}

but I wish to get

{"foo":42}

Is it possible to get around the problem in some easy way?

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"
}

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.

I will only add that you can generate those tags automatically using gopls . It is a menial task to add the tags manually, especially with large json structs, so the feature is a live-saver.

You can generate the json:"camelCase" tags of struct fields with fatih/gomodifytags .

eg

$ gomodifytags -file main.go -struct T -add-tags json -transform camelcase -quiet -w

NB: You can also use -override to override existing tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM