Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
BlasterAlex opened this issue May 29, 2023 · 0 comments
Open

Comments

@BlasterAlex
Copy link

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

@BlasterAlex BlasterAlex changed the title Marshal applies omitempty tag to all fields of embedded struct Marshal ignores fields on embedded struct when using an omitempty tag May 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant