How to marshal an empty json object without omitting it?

2,992 views
Skip to first unread message

yic...@gmail.com

unread,
Feb 16, 2015, 5:26:47 PM2/16/15
to golan...@googlegroups.com
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!

Yves Junqueira

unread,
Feb 16, 2015, 5:38:45 PM2/16/15
to yic...@gmail.com, golang-nuts
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.


--
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...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Reply all
Reply to author
Forward
0 new messages