FAQ
Hi,

One of the tag options you can specify to encoding/json<http://golang.org/pkg/encoding/json/>is "string":

The "string" option signals that a field is stored as JSON inside a
JSON-encoded string.

While this works as I expect ints and strings, it doesn't have any effect
on the encoding of struct, map, or slice values. For instance, if I have
this struct:

type A struct {
S []int `json:",string"`
}

then I would expect it to be encoded the following way:

&A{[]int{1,2,3}} // =>
{"S":"[1,2,3]"}

that is, the string value to be inside a JSON string (and quotes escaped if
necessary).

Am I not understanding the documentation correctly? From looking at the
code (and experimentation), structs, maps, and slices will not be quoted
when the 'string' option is set.

Here's a play that shows a short example with structs:

http://play.golang.org/p/YcBmoBVVmW

And here's another showing how it works for ints and strings, but not for
maps and slices:

http://play.golang.org/p/YRlOeHsanD

Thanks!
-Caleb

--

Search Discussions

  • Russ Cox at Nov 25, 2012 at 7:28 pm
    I think the ,string option only applies to basic types like int and
    float; the documentation needs to be updated.

    Russ

    --
  • Caleb Spare at Nov 26, 2012 at 4:07 pm
    Thanks Russ.

    Is there some reason that ,string should not (or cannot) work for more
    complex types?

    -Caleb
    On Sunday, November 25, 2012 11:28:51 AM UTC-8, Russ Cox wrote:

    I think the ,string option only applies to basic types like int and
    float; the documentation needs to be updated.

    Russ
    --
  • Dustin Sallings at Nov 26, 2012 at 5:58 pm

    Caleb Spare writes:

    Is there some reason that ,string should not (or cannot) work for more
    complex types?
    What would you want it to do? A JSON encoding as a JSON string? %v?
    %+v? %#v?

    --
    dustin

    --
  • Caleb Spare at Nov 26, 2012 at 6:12 pm

    On Monday, November 26, 2012 9:52:09 AM UTC-8, Dustin wrote:

    Caleb Spare <ces...@gmail.com <javascript:>> writes:
    Is there some reason that ,string should not (or cannot) work for more
    complex types?
    What would you want it to do? A JSON encoding as a JSON string? %v?
    %+v? %#v?
    A JSON encoding as a JSON string, as the documentation states.

    --
    dustin
    --
  • Russ Cox at Nov 29, 2012 at 8:54 pm

    Is there some reason that ,string should not (or cannot) work for more
    complex types?
    It just adds complexity. Next we'll need ,string,string. I'm sad we
    even have ,string in the first place: it was added because it is very
    common in some protocols to send numbers as strings to avoid
    floating-point representation issues.

    Russ

    --

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedNov 12, '12 at 10:27p
activeNov 29, '12 at 8:54p
posts6
users3
websitegolang.org

People

Translate

site design / logo © 2022 Grokbase