ANisus
ANisus

Reputation: 78025

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?

Upvotes: 228

Views: 70435

Answers (5)

Dennis Gloss
Dennis Gloss

Reputation: 2841

My library fetch is a simple HTTP client to handle JSON APIs. To omit json tags, fetch.Marshal automatically parses struct fields as lowercase.

type T struct {
    Foo int
}
out, err := fetch.Marshal(T{Foo: 42})
if err != nil {
    panic(err) 
}
fmt.Println(out) // {"foo":42}

Upvotes: 0

Letik
Letik

Reputation: 540

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

e.g.

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

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

Upvotes: 0

Piotr
Piotr

Reputation: 712

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.

Upvotes: 6

jimt
jimt

Reputation: 26427

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

Upvotes: 340

Lily Ballard
Lily Ballard

Reputation: 185721

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.

Upvotes: 10

Related Questions