Convert Json.Number into int/int64/float64 in golang
18,273
Check this documentation to know the available methods on json.Number
:
https://golang.org/pkg/encoding/json/#Number
f, err := data.(json.Number).Float64()
Related videos on Youtube
Author by
KuZon
Updated on September 16, 2022Comments
-
KuZon over 1 year
I have a variable data, which is an interface. When I print its type I get it as json.Number. How do I type cast to int/int64/float64
If I try data.(float64), it ends up with panic error
panic: interface conversion: interface {} is json.Number, not float64
-
mkopriva over 6 years
data.(json.Number).Int64()
You type assert to the actual underlying type, not to an arbitrary type you wish it was. That means that if an interface's underlying type isjson.Number
you type assert it asjson.Number
. And alsov.(T)
in Go is not conversion but type assertion. -
mkopriva about 5 years@horsehair because Go doesn't know the underlying type at compile type and type assertion is a test that helps you figure out the underlying type of an interface value at runtime. This is useful if you need to use the "features" of the underlying type as opposed to the "features" of the interface type.
-
mkopriva about 5 years@horsehair panic's are runtime errors, not compile time errors.
-
mkopriva about 5 years@horsehair type information is stored in Go's runtime system. Also while
json.Number
's underlying type may bestring
the two types are not the same and so type-asserting one to the other is bound to fail, however converting one to the other is ok.
-
-
0x574F4F54 about 6 yearsAs a newcomer to go, an example like this is exactly what I needed. While the documentation referenced is accurate, it lacks a straight-forward demonstration of how to use the functionality. Thanks!