decimal icon indicating copy to clipboard operation
decimal copied to clipboard

Json tag omitempty does not work for decimal

Open focusonline opened this issue 2 years ago • 3 comments

Although there is omitempty tag decoration in decimal type, and the value is 0 or not fetched from table, but the result is always "0". I checked the source code, it does not consider the tag of Json and omitempty when MarshalJSON, see below:

func (d Decimal) MarshalJSON() ([]byte, error) {
	var str string
	if MarshalJSONWithoutQuotes {
		str = d.String()
	} else {
		str = "\"" + d.String() + "\""
	}
	return []byte(str), nil
}

Is it a problem? thanks! :)

focusonline avatar Mar 29 '22 11:03 focusonline

The type Decimal though acts and sounds like an int/float, but is actually a struct. This means encoding/json won't omit it unless you make the field a pointer and send nil into it.

The isEmptyValue() in line 750 returns true (required to omit) only if field is a pointer to struct and a nil is sent as value.

struct {
	Number *decimal.Decimal `json:"number,omitempty"`
}{
	Number: nil,
}

Control reaches MarshalJSON only when isEmptyValue() == false, i.e., encoding/json is not omitting the field. Controlling the behavior in MarshalJSON won't help.

vaguecoder avatar Aug 01 '22 14:08 vaguecoder

@vaguecoder I found your comment really helpful. I was running into the same thing with xml. Using a *decimal.Decimal solved my issue. A really excellent explanation here. Thanks.

mk-j avatar Dec 13 '22 21:12 mk-j

@vaguecoder I found your comment really helpful. I was running into the same thing with xml. Using a *decimal.Decimal solved my issue. A really excellent explanation here. Thanks.

@mk-j I'm glad. Thanks for letting me know. 😊

vaguecoder avatar Dec 14 '22 12:12 vaguecoder