简体   繁体   English

小写 JSON 键名加上 JSON Marshal in Go

[英]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.我希望使用"encoding/json" package 编组在我的应用程序的一个导入包中声明的结构。

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} {“富”:42}

but I wish to get但我希望得到

{"foo":42} {“富”:42}

Is it possible to get around the problem in some easy way?是否有可能以某种简单的方式解决这个问题?

Have a look at the docs for encoding/json.Marshal .查看encoding/json.Marshal的文档。 It discusses using struct field tags to determine how the generated json is formatted.它讨论了使用结构字段标签来确定生成的 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"
}

You could make your own struct with the keys that you want to export, and give them the appropriate json tags for lowercase names.您可以使用要导出的键创建自己的结构,并为它们提供适当的 json 标记以表示小写名称。 Then you can copy the desired struct into yours before encoding it as JSON.然后,您可以将所需的结构复制到您的结构中,然后再将其编码为 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.或者,如果您不想费心制作本地结构,您可以制作一个map[string]interface{}并对其进行编码。

I will only add that you can generate those tags automatically using gopls .我只会补充一点,您可以使用gopls自动生成这些标签。 It is a menial task to add the tags manually, especially with large json structs, so the feature is a live-saver.手动添加标签是一项微不足道的任务,尤其是对于大型 json 结构,因此该功能可以节省时间。

You can generate the json:"camelCase" tags of struct fields with fatih/gomodifytags .您可以使用fatih/gomodifytags生成结构字段的json:"camelCase"标签。

eg例如

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

NB: You can also use -override to override existing tags.注意:您还可以使用-override来覆盖现有标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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