segmentio / encoding

Go package containing implementations of efficient encoding, decoding, and validation APIs.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Marshal ignores fields on embedded struct when using an omitempty tag

BlasterAlex opened this issue · comments

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