go-json-experiment / json

Experimental implementation of a proposed v2 encoding/json package
BSD 3-Clause "New" or "Revised" License
390 stars 13 forks source link

Option for Customizing Field Omission #24

Open inoc603 opened 7 months ago

inoc603 commented 7 months ago

The new omitzero behavior is very nice, but it can only be defined using tags. Can we introduce a new option to modify the behavior, e.g. treat omitempty as omitzero, so structs imported from another package can be marshaled with the new omitzero behavior?

dsnet commented 7 months ago

I think something like this is reasonable. Probably an option like "OmitZeroStructFields".

dsnet commented 6 months ago

I analyzed all public Go code known by the proxy as of 2024-04-01 for existing json struct tags. This is the number of each combination of tags:

Percent Count Tag combination
49.9% 26260569 name,omitempty
44.2% 23290292 name
5.4% 2821440 -
0.3% 136470 ,inline
0.2% 114903 ,omitempty
0.0% 14071
0.0% 6261 ,omitempty,inline
0.0% 266 name,inline
0.0% 115 name,omitzero
0.0% 97 name,omitzero,omitempty
0.0% 68 name,omitempty,inline
0.0% 1 ,format

It seems that omitempty or omitzero is present in about half of all fields with an explicit json tag.

EDIT: I removed occurrences within test files.