JSON empty slice and/or empty set encoding question/proposal

73 views
Skip to first unread message

traetox

unread,
Mar 27, 2017, 12:42:46 PM3/27/17
to golang-nuts
Hello all,

I have swept through the list and gone through the pkg/encoding/json package and _believe_ I haven't missed anything, but am not 100% sure.

When encoding structures into JSON which contain slices/arrays/maps my frontend devs consistently complain about the encoding of empty or nil members which they have to do a little extra work to deal with.

For example, structure is defined as:

type Foo Struct {
     Bar []string
     Baz map[string]int
}

if any of the members of the struct (Bar, Baz) are not initialized, or empty the encoding is:

{
    "Bar": null,
    "Baz": null,
}

What they want is :

{
    "Bar": [],
    "Baz": {},
}

The frontend guys complain because they can't just hand that structure to some of their libraries.  I have been getting around this by defining custom marshallers for each type which detect empty or null items and marshal them out as '[]' and '{}' respectively.  I know the other option is to just ensure an empty map/slice/array is initialized but invoking potential allocations and GC seems wasteful.  Is there a json directive that can be attached that tells the standard library marshaller to always render empty items into a '[]', '{}', etc. similar to the omitempty  directive?

If not, would there be any support for me to propose, develop, and submit a patch to do so?

As always, thank you all for the great work on Golang and the standard library!
Kris

C Banning

unread,
Mar 30, 2017, 11:10:38 AM3/30/17
to golang-nuts
Why not provide a "NewFoo() *Foo" function instead? https://play.golang.org/p/GE8cMgwe24

traetox

unread,
Mar 30, 2017, 11:22:19 AM3/30/17
to golang-nuts
That does indeed work, but requires a call to "NewFoo" every time i marshal (invoking an allocation and subsequent GC).
The application I am building is extremely memory intensive so I would like to be able to avoid that.

I am totally willing to put in the work on the standard library Marshaller, as enabling a JSON renderer flag like "renderempty" doesn't require developers to go track down every marshal invocation for a type to ensure the rendered JSON matches what the web guys want.

Basically, I am waiting for some of the higher ups to say "no we won't support that patch" or "sure, go for it."

Thank you,
Kris
Reply all
Reply to author
Forward
0 new messages