Marshal float64 onto json in Go

huangapple go评论69阅读模式
英文:

Marshal float64 onto json in Go

问题

我在Go语言中有一个struct,其中包含一个float64字段。然而,当我将该字段的值编组到JSON对象时,它给我返回一个指数形式的数字。
根据我对类似问题的研究,我了解到在JSON对象中它将是一个数字,在Go语言中它将是一个float64,然而我不太明白如何读取实际的数字而不是一个float64
这是我的代码示例。

http://play.golang.org/p/pR1B2oBKw2

它显示了一个具有相同值的字符串和float64,我只想在我的JSON对象上正确显示float64
我在这个论坛上找到了类似的问题,但似乎没有一个直接的答案。它们对我来说都是一些变通方法,并且与反编组对象相关,而不是反之。

英文:

I have a struct in go which contains a float64 field. However when I marshal the value of this field onto a json object it gives me a exponential number.
Based on my research on people with similar issues here, I understand that in json objects it will be number and in go it will be a float64, however I don't quite understand how to read the actual number and not a float64.
Here's a sample of my code.

http://play.golang.org/p/pR1B2oBKw2

It shows a string and a float64 both with the same values and all I want is the float64 to be dislpayed correctly on my json object.
I have found similar questions on this forum but none of them seems to have a straight forward answer. They all seems to be workarounds to me and are related to unmarshaling an object and not the other way around.

答案1

得分: 5

翻译结果如下:

简短版本,你不能。

长版本?创建你自己的类型!

type FloatString float64

func (fs FloatString) MarshalJSON() ([]byte, error) {
    vs := strconv.FormatFloat(float64(fs), 'f', 2, 64)
    return []byte(`"` + vs + `"`), nil
}

func (fs *FloatString) UnmarshalJSON(b []byte) error {
    if b[0] == '"' {
        b = b[1 : len(b)-1]
    }
    f, err := strconv.ParseFloat(string(b), 64)
    *fs = FloatString(f)
    return err
}

playground

英文:

Short version, you can't.

Long version? create your own type!

type FloatString float64

func (fs FloatString) MarshalJSON() ([]byte, error) {
	vs := strconv.FormatFloat(float64(fs), 'f', 2, 64)
	return []byte(`"` + vs + `"`), nil
}

func (fs *FloatString) UnmarshalJSON(b []byte) error {
	if b[0] == '"' {
		b = b[1 : len(b)-1]
	}
	f, err := strconv.ParseFloat(string(b), 64)
	*fs = FloatString(f)
	return err
}

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2015年8月19日 09:51:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/32085288.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定