segmentio/encoding

Marshal silently encodes bad JSON for embedded null pointer structs (works in encoding/json)

anthonyrisinger opened this issue · 3 comments

While playing around with struct embedding and omitempty I discovered Marshal emits an erroneous comma for embedded null pointer structs (unless they're first, maybe in other situations too).

See https://play.golang.org/p/21NWHuHchQq or the example below.

package main

import (
	"encoding/json"
	"fmt"
	segjson "github.com/segmentio/encoding/json"
)

type N struct {
	Zero int
	*One
	Two int
}

type One struct {
	One int
}

func main() {
	data, err := segjson.Marshal(N{Two: 2})
	fmt.Println(string(data))
	fmt.Println(err)
	
	data, err = json.Marshal(N{Two: 2})
	fmt.Println(string(data))
	fmt.Println(err)
}

The above produces this output:

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

Thanks a lot for reporting @anthonyrisinger!

I'll start working on a fix (unless you've got something already).

I only just bumped into it tonight, and haven't looked too much further -- it's not blocking me -- feel free to get started!

@achille-roussel Created PR #42 to fix it along with the above mentioned test case. Kindly review it, if you already haven't made a patch to fix it.