goccy / go-json

Fast JSON encoder/decoder compatible with encoding/json for Go
MIT License
3.11k stars 148 forks source link

Invalid JSON produced when embedding structs (inline) #486

Open antonsacred opened 1 year ago

antonsacred commented 1 year ago

Case 1

type Structure struct {
    Id int `json:"id"`
    *Structure
}

func TestIssueWithInlineStruct(t *testing.T) {
    obj := Structure{
        Id: 99,
    }

    b, err := json.Marshal(obj)
    assertErr(t, err)
    assertEq(t, "key a", `{"id":99,null}`, string(b))

    // compare with standard library
    b, err = stdjson.Marshal(obj)
    assertErr(t, err)
    assertEq(t, "key b", `{"id":99}`, string(b))
}

Case 2

type AlternativeStructure struct {
    Id int `json:"id"`
    *Structure
}

type Structure struct {
    Id          int                  `json:"id"`
    Alternative AlternativeStructure `json:"alternative"`
}

func TestIssueWithInlineStruct(t *testing.T) {
    obj := Structure{
        Id:          99,
        Alternative: AlternativeStructure{Id: 123},
    }

    b, err := json.Marshal(obj)
    assertErr(t, err)
    assertEq(t, "key a", `{"id":99,"alternative":{"id":123,null}}`, string(b))

    // compare with standard library
    b, err = stdjson.Marshal(obj)
    assertErr(t, err)
    assertEq(t, "key b", `{"id":99,"alternative":{"id":123}}`, string(b))
}

When structure in embedded to itself go-json produce invalid json {"id":123,null}