Golang JSON Tags

Suppose I have a Foo structure.

 Foo struct { Bar, Baz int } 

And I want to combine this structure in json as follows: {bar : 1, baz : 2}

How could I achieve this without breaking a single declaration of several lines ( Bar, Baz int ) into two separate lines using tags.

It works:

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

But I would like to:

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

Is the last possible?

+7
go
source share
2 answers

According to the specification , No.

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

go has a strict syntax favoring one way to do something.

+12
source share

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

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

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

edit: As tarrsalla said below, prefer the β€œone way to do something” and it will be better for you if you used this β€œpath”

-one
source share

All Articles