Lowercase JSON key names with JSON Marshal in Go

Viewed 56701

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?

3 Answers

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.

Adding the gopls langserver differs based on one's preferred editor. After:

go install golang.org/x/tools/gopls@latest

For Neovim with CoC you can :CocInstall coc-go and then go.tags.add. For complete docs on the CoC extension for go please see here.

Related