Skip to content

Marshal ignores fields on embedded struct when using an omitempty tag #133

@BlasterAlex

Description

@BlasterAlex

If you use an embedded struct via a pointer and omitempty tag on one of struct fields, fields on embedded struct which also tagged with omitempty are ignored in the output json, even if there is a value.

Example code:

package main

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

type A struct {
	Surname string `json:"surname,omitempty"`
}

type B struct {
	*A
	MiddleName string `json:"middle-name,omitempty"`
	Name       string `json:"name"`
}

func main() {
	a := &A{Surname: "surname"}
	b := B{A: a, Name: "name"}

	r1, err := json.Marshal(b)
	fmt.Printf("json: %s, err: %v\n", r1, err)

	r2, err := segjson.Marshal(b)
	fmt.Printf("segmentio: %s, err: %v\n", r2, err)
}

Example output:

json: {"surname":"surname","name":"name"}, err: <nil>
segmentio: {"name":"name"}, err: <nil>

Notes:

  • Not reproduced if structure A is used by value and not by reference
  • Not reproduced if MiddleName field is declared after Name field
  • Not reproduced if MiddleName field has value

Go: go1.20
segmentio/encoding/json: v0.3.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions