serializing to json
Tim Penhey
tim.penhey at canonical.com
Wed Apr 1 00:01:50 UTC 2015
On 01/04/15 08:22, Nate Finch wrote:
> FYI:
>
> Serializing a struct to json works without having to specify struct tags:
>
> type foo struct {
> Name string
> Age int
> }
>
> f := foo{ "Bob", 40 }
>
> serializes ("marshals") into
>
> {
> "Name" : "Bob",
> "Age" : 40
> }
>
> No struct tags needed. The only time you need struct tags is if you
> want to change the json name of one of the fields from being the same as
> the field name. This is most commonly done to lowercase the field names
> when interoperating with an existing json service. Note that only
> exported fields can be marshaled/unmarshaled, which is why you often see
> stuff like this:
>
> type foo struct {
> Name string `json:"name"`
> Age int `json:"age"`
> }
>
> This lets the json package translate from the lowercase json name to the
> uppercase field name (and vice versa). But when we control both ends of
> serialization (like in the api params package), we don't need to
> lowercase anything (in which case we can leave out the struct tags
> entirely).
>
> Struct tags that are the same as the name of field are never needed:
>
> type SomeResult struct {
> Error *Error `json:"Error"`
> Somethings []Something `json:"Somethings"`
> }
>
> The above is totally unnecessary... those fields will already serialize
> into "Error" and "Somethings". There's a bunch of this in the
> apiserver/params package... you don't need it, so don't do it. It just
> causes confusion, because it looks like you're changing the name from
> the default, even though you're not.
Actually it was William who originally suggested and started enforcing
explicit over implicit with respect to the serialization directives.
YAML and JSON serialize differently by default, and being explicit means
you don't have to think about it.
Generally, for our serialization directives there is a preference for
lower case, and I'd recommend this for all new directives. The above
explicit directives were probably added for the explicit nature, but
upper case so it matches works with the older clients.
Personally I am strongly in favour of explicit over implicit.
Tim
More information about the Juju-dev
mailing list