Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang JSON tags

Tags:

go

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?

like image 572
if __name__ is None Avatar asked Dec 02 '13 22:12

if __name__ is None


1 Answers

According to the specification, No.

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

go has a strict syntax favouring the one way to do things.

like image 107
Salah Eddine Taouririt Avatar answered Nov 07 '22 05:11

Salah Eddine Taouririt