Go中包含JSON Marshal的小写JSON键名 [英] Lowercase JSON key names with JSON Marshal in Go

查看:314
本文介绍了Go中包含JSON Marshal的小写JSON键名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用encoding / json包来封送在我的应用程序的一个导入包中声明的结构。



例如:

  type T struct {
Foo int
}

因为它被导入,结构中所有可用(导出)字段都以大写字母开头。但我希望有小写键名:

  out,err:= json.Marshal(& T {Foo:42 })

将导致


{Foo:42}


但我希望获得


{foo:42}

是否可以避开问题在一些简单的方法?

解决方案

查看文档 encoding / json.Marshal
它讨论了使用struct字段标记来确定生成的json的格式。



例如:

< pre $ type T struct {
FieldA int`json:field_a`
FieldB string`json:field_b,omitempty`
}

这将生成JSON,如下所示:

  {
field_a:1234,
field_b:foobar
}


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?

解决方案

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

这篇关于Go中包含JSON Marshal的小写JSON键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆