Skip to content

Two commas and no error

 1 min A nil embedded Go pointer made one JSON encoder emit an extra comma; comparing the same value with the standard encoder isolated it.
Published

Aug 4, 2020

While experimenting with Go struct embedding, I found a JSON encoder returning malformed output with a nil error. The value had an embedded pointer between two ordinary fields:

type N struct {
    Zero int
    *One
    Two int
}

type One struct { One int }

The reproducer marshaled N{Two: 2} through Segment’s encoder and Go’s encoding/json:

{"Zero":0,,"Two":2}
<nil>
{"Zero":0,"Two":2}
<nil>

The absent embedded value contributed no fields, but the first encoder left an extra separator where those fields would have been. Putting the nil pointer between populated fields exposed the state transition that a simpler all-empty or first-field case could miss.

The standard encoder gave the report a direct comparison. It was still important to inspect the bytes: both calls returned nil errors, so a test that checked only the error values would pass.

Another contributor supplied the fix and regression case. My contribution was the report and the small input that made the divergence visible. The test did not need an application-sized fixture; it needed the empty embedded object in the position where separator bookkeeping mattered.