FAQ
Hello,

How do I marshal a struct field as an empty json object? For example,

type Person struct {
     Name string `json:"name"`
     Meta map[string]interface{} `json:"meta"`
}


When I marshal this struct to JSON, I would like to keep the "meta" field
as empty json object, like "{}", if it is an empty map, instead of null or
being omitted (using omitempty).

{
     "name" : "tester",
     "meta": {}
}


Here is the quick sample in playground: http://play.golang.org/p/VRtnY8Ww2s

Thanks!

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

  • Yves Junqueira at Feb 16, 2015 at 10:38 pm
    Your question refers to an "empty map", but then you didn't provide the map
    at all. There's a difference between an empty map and a nil map. This works:

    p := Person{
    Name: "tester",
    Meta: map[string]interface{}{}, // the map is non-nil, but empty.
    }

    And has the effect of producing:

    {
         "name": "tester",
         "meta": {}
    }


    I hope that helps.

    On Mon, Feb 16, 2015 at 11:26 PM, wrote:

    Hello,

    How do I marshal a struct field as an empty json object? For example,

    type Person struct {
    Name string `json:"name"`
    Meta map[string]interface{} `json:"meta"`
    }


    When I marshal this struct to JSON, I would like to keep the "meta" field
    as empty json object, like "{}", if it is an empty map, instead of null or
    being omitted (using omitempty).

    {
    "name" : "tester",
    "meta": {}
    }


    Here is the quick sample in playground:
    http://play.golang.org/p/VRtnY8Ww2s

    Thanks!

    --
    You received this message because you are subscribed to the Google Groups
    "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an
    email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/d/optout.


    --
    Yves Junqueira <http://google.com/+YvesJunqueira>

    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/d/optout.

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedFeb 16, '15 at 10:26p
activeFeb 16, '15 at 10:38p
posts2
users2
websitegolang.org

2 users in discussion

Yves Junqueira: 1 post Yichen: 1 post

People

Translate

site design / logo © 2022 Grokbase