Preserving Trailing Zeros in JSON Output for Floating-Point Numbers
In Go, the json.Marshal() function is commonly used for serializing data structures into JSON format. However, it has a tendency to strip trailing zeros from floating-point numbers during the conversion process. This can be a problem if the consuming application expects the numbers to have trailing zeros.
To address this issue, one approach is to create a custom floating-point type that implements the json.Marshaler interface. This allows you to define how the type is serialized into JSON. Here's an example implementation:
type KeepZero float64 func (f KeepZero) MarshalJSON() ([]byte, error) { if float64(f) == float64(int(f)) { return []byte(strconv.FormatFloat(float64(f), 'f', 1, 32)), nil } return []byte(strconv.FormatFloat(float64(f), 'f', -1, 32)), nil }
In this code:
To use the KeepZero type, you can replace the original float64 field in your data structure with a KeepZero field. For example:
type Pt struct { Value KeepZero Unit string }
When you call json.Marshal on a Pt object, the Value field will be serialized using the custom MarshalJSON method, preserving the trailing zero if necessary.
data, err := json.Marshal(Pt{40.0, "some_string"}) fmt.Println(string(data), err)
This will produce the following JSON output:
{"Value":40.0,"Unit":"some_string"}
This solution allows you to retain the trailing zeros in your floating-point numbers when serializing them to JSON, as required by the consuming application.
The above is the detailed content of How to Preserve Trailing Zeros in JSON Output for Go\'s Floating-Point Numbers?. For more information, please follow other related articles on the PHP Chinese website!