Go 中带有 JSON Marshal 的小写 JSON 键名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11693865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lowercase JSON key names with JSON Marshal in Go
提问by ANisus
I wish to use the "encoding/json"package to marshal a struct declared in one of the imported packages of my application.
我希望使用该"encoding/json"包来编组在我的应用程序的导入包之一中声明的结构。
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}
{"Foo":42}
but I wish to get
但我希望得到
{"foo":42}
{"foo":42}
Is it possible to get around the problem in some easy way?
是否有可能以某种简单的方式解决这个问题?
回答by jimt
Have a look at the docs for encoding/json.Marshal. It discusses using struct field tags to determine how the generated json is formatted.
查看encoding/json.Marshal的文档。它讨论了使用 struct 字段标签来确定生成的 json 的格式。
For example:
例如:
type T struct {
FieldA int `json:"field_a"`
FieldB string `json:"field_b,omitempty"`
}
This will generate JSON as follows:
这将生成如下 JSON:
{
"field_a": 1234,
"field_b": "foobar"
}
回答by Lily Ballard
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.
您可以使用要导出的键创建自己的结构,并为小写名称提供适当的 json 标签。然后,您可以将所需的结构复制到您的结构中,然后再将其编码为 JSON。或者,如果您不想费心制作本地结构,您可以制作一个map[string]interface{}并对其进行编码。

