patterngoCritical
Lowercase JSON key names with JSON Marshal in Go
Viewed 0 times
keywithjsonlowercasemarshalnames
Problem
I wish to use the
Eg.:
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:
will result in
{"Foo":42}
but I wish to get
{"foo":42}
Is it possible to get around the problem in some easy way?
"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?
Solution
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:
This will generate JSON as follows:
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"
}Code Snippets
type T struct {
FieldA int `json:"field_a"`
FieldB string `json:"field_b,omitempty"`
}{
"field_a": 1234,
"field_b": "foobar"
}Context
Stack Overflow Q#11693865, score: 342
Revisions (0)
No revisions yet.