停止json.Marshal()从浮点数剥离尾随零 [英] Stop json.Marshal() from stripping trailing zero from floating point number
问题描述
我遇到以下问题: 我的golang程序将一些信息转换为JSON. 例如,它导致以下json:
I got the following problem: My golang program converts some information into JSON. For example it results in the following json:
{
"value":40,
"unit":"some_string"
}
问题是值的输入"为40.0,编组剥离了结尾的零.如果读取JSON的EPL能够将浮点数读取为40而没有.0
The problem is the "input" for value is 40.0 and the marshalling strips the trailing zero. It would be no problem if the EPL which reads the JSON would be able to read 40 as float without the .0
因此JSON输出应类似于:
So the JSON output should look like:
{
"value":40.0,
"unit":"some_string"
}
是否有可能阻止" json.Marshal()删除零?
Is there a possibility to "stop" json.Marshal() from removing the zero?
值必须是浮点数
推荐答案
@icza提供了一个很好的答案,但只是提供了另一个选择,您可以定义自己的float类型并为其定义序列化.像这样
@icza provided a good answer, but just to offer another option, you can define your own float type and define your own serialization for it. Like this
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
}
type Pt struct {
Value KeepZero
Unit string
}
func main() {
data, err := json.Marshal(Pt{40.0, "some_string"})
fmt.Println(string(data), err)
}
这将导致{"Value":40.0,"Unit":"some_string"} <nil>
. 在操场上查看.
这篇关于停止json.Marshal()从浮点数剥离尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!