JSon and multiple name tags

1,084 views
Skip to first unread message

Yohann Coppel

unread,
Feb 20, 2012, 6:30:07 PM2/20/12
to golan...@googlegroups.com
Hello,

When using the json encoder, you probably know that you can write this:
type Object struct {
  Field int32 `json:"externalField"`
}

And when (de)serialized, the json package will use the name "externalField" instead of "Field".
For example, it will parse/generate the following json:
{ "externalField": 123 }

However, what about when two fields are declared on the same line, such as:
type Point struct {
  X, Y, Z int32
}

Is it possible to use tags in that case ? The spec says that the tag "becomes an attribute for all the fields in the corresponding field declaration."
Which means that X, Y and Z will get the same tag.

I tried to specify different json tags like this:
type Point struct {
  X, Y, Z int32 `json:"x",json:"y",json:"z"`
}
but it didn't work.
I am guessing the json package doesn't even get the information that field Y, with the tag `json:"x",json:"y",json:"z"`, was the second in a list of fields.

Bug ? Feature ? Me being silly (could be... I mean, at this point, I should just break the declaration in multiple lines as it would be more clear... but curiosity :) ) ?

Thanks.

Yohann Coppel

unread,
Feb 20, 2012, 6:33:28 PM2/20/12
to golan...@googlegroups.com
As a related question: I am mostly interested into lower-casing all my field names. Any other better/quicker way of doing that ?

Andrew Gerrand

unread,
Feb 20, 2012, 6:40:36 PM2/20/12
to Yohann Coppel, golan...@googlegroups.com
On 21 February 2012 10:30, Yohann Coppel <yoh...@gmail.com> wrote:
> Bug ? Feature ? Me being silly (could be... I mean, at this point, I should
> just break the declaration in multiple lines as it would be more clear...
> but curiosity :) ) ?

Just the way it is. You need to specify the fields on separate lines.

On 21 February 2012 10:33, Yohann Coppel <yoh...@gmail.com> wrote:
> As a related question: I am mostly interested into lower-casing all my field
> names. Any other better/quicker way of doing that ?

No.

Andrew

Yohann Coppel

unread,
Feb 20, 2012, 8:25:16 PM2/20/12
to golan...@googlegroups.com, Yohann Coppel
Thanks for the quick reply !
Cheers.
Reply all
Reply to author
Forward
0 new messages