13

Does Go correct marshal float64 to JSON?

 3 years ago
source link: https://www.codesd.com/item/does-go-correct-marshal-float64-to-json.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Does Go correct marshal float64 to JSON?

advertisements

Using go1.1.2 Win64, I have a Go program that "marshal"'s a struct containing a float64. When the value of the float64 is not a whole number eg. 1234.44, then it gets "marshal"ed as a float (json.Marshal). When however it is a whole number eg. "1234.00" it is marshalled as an integer"1234". When I receive that at the other end (Dart), Dart (30188) treats the whole number as an integer (in map - JSON.decode). Consequently the Dart program aborts when the representation of the float (double) data doesn't contain a decimal point, and I attempt to "extract" it from the map as a double.

This can obviously be solved a number of different ways (eg. convert to integer and then convert back to float), however I wondered if there is another (better) way to handle this situation.

Is there another better way to handle this than to convert float64 to integer?


JSON, just like Javascript, doesn't differ between integers and numbers.

If Dart treats 1234.00 differently from 1234, then it is making assumptions about the value not supported by the JSON specification.

While Go does indeed marshal float64 correctly, one way of getting around the problem with Dart's assumption is by implementing the Marshaler interface on your own type:

type Number float64

func (n Number) MarshalJSON() ([]byte, error) {
    // There are probably better ways to do it. It is just an example
    return []byte(fmt.Sprintf("%f", n)), nil
}

And then you can use your own Number type, instead of float64, in the structs that you will Marshal. This way you can make sure that your numbers will always be marshaled with a decimal point.

Working example on Playground


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK