Skip to content

Panic when marshaling nested struct with empty slice and omitempty tag #554

@Matty12138

Description

@Matty12138

Description​​:

When marshaling a deeply nested struct that contains an empty slice with omitemptytag, go-json panics with "invalid memory address or nil pointer dereference". The standard encoding/jsonhandles this case correctly.

​​Minimal Reproduction​​:

package main

import (
	encodingjson "encoding/json"
	"fmt"
	gojson "github.com/goccy/go-json"
)

func main() {
	grandpa := Grandpa{}
	raw1, _ := encodingjson.Marshal(&grandpa)  // works
	raw2, _ := gojson.Marshal(&grandpa)       // panics
	fmt.Println(string(raw1), string(raw2))
}

type Grandpa struct { Father }
type Father struct {
	Son
	A []string `json:"a,omitempty"` // panic occurs with empty slice + omitempty
}
type Son struct {
	B string `json:"b"` // required for panic
	C string `json:"c"` // required for panic
}

Observations​​:

1.Panic occurs with:

  • Deeply nested structs
  • Empty slice with omitemptytag
  • Certain field combinations in child structs

2.Works fine if:

  • Not using nested structs
  • Removing omitempty
  • Making slice non-empty
  • Removing certain fields from child struct

​​Expected Behavior​​:

Should marshal without panic, like encoding/json.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions