Golang的JSON标签

huangapple go评论83阅读模式
英文:

Golang JSON tags

问题

假设我有一个结构体 Foo

Foo struct {
        Bar, Baz int
}

我想将这个结构体编组成 json,如下所示:
{bar : 1, baz : 2}

如何实现这一点,而不需要将我的单行多个名称声明 (Bar, Baz int) 拆分成两行,并使用标签。

这样可以实现:

Foo struct {
        Bar int `json:"bar"`
        Baz int `json:"baz"`
}

但我想要的是:

Foo struct {
        Bar, Baz int `json:???`
}

后者是否可能?

英文:

Suppose I have a struct Foo.

Foo struct {
        Bar, Baz int
}

And I want to marshal this struct into json like so:
{bar : 1, baz : 2}

How could I achieve that, without splitting my single line multiple name declaration (Bar, Baz int) into 2 separate lines using tags.

This works:

> Foo struct {
> Bar int json:"bar"
> Baz int json:"baz"
> }

But I'd like:

> Foo struct {
> Bar, Baz int json:???
> }

Is the latter even possible?

答案1

得分: 12

根据[规范][1],不。

StructType     = "struct" "{" { FieldDecl ";" } "}" .
FieldDecl      = (IdentifierList Type | AnonymousField) [ Tag ] .
AnonymousField = [ "*" ] TypeName .
Tag            = string_lit .

[tag:go] 有一个严格的语法,偏向于一种做事情的方式。
[1]: http://golang.org/ref/spec#Struct_types

英文:

According to the [specification][1], No.

StructType     = "struct" "{" { FieldDecl ";" } "}" .
FieldDecl      = (IdentifierList Type | AnonymousField) [ Tag ] .
AnonymousField = [ "*" ] TypeName .
Tag            = string_lit .

[tag:go] has a strict syntax favouring the one way to do things.
[1]: http://golang.org/ref/spec#Struct_types

答案2

得分: -1

Go语言内置了一个名为encoding/json的包,可以帮助你处理这种情况。

这是该库的Godocs文档:http://golang.org/pkg/encoding/json/

这是我使用该库创建的一个示例:http://play.golang.org/p/YOhj2qKg-2

编辑:正如tarrsalla在我下面所说的,Go更倾向于“一种方法来做事”,如果你使用那种方法,长远来看会更好。

英文:

Go has a built in package encoding/json that can help you out in this situation.

Here is the godocs for the library http://golang.org/pkg/encoding/json/

Here is an example I made using the library http://play.golang.org/p/YOhj2qKg-2

edit: As tarrsalla said below me, go prefers the "one way to do things" and it would work out better for you in the long run if you used that "way"

huangapple
  • 本文由 发表于 2013年12月3日 06:23:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/20339117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定