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?
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.
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"