The following code to un-marshall json data from from byte array changing the type of float value to int.
package main
import (
"encoding/json"
"fmt"
)
func main() {
byt := []byte(`{"num":6.0}`)
var dat map[string]interface{}
fmt.Println(byt)
if err := json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
fmt.Println(dat)
}
Here is the playground link: https://go.dev/play/p/60YNkhIUABU
Is there anyway to keep the type as it is?
CodePudding user response:
The unmarshalled number already is a float64
. You can check this by adding a line to the end of your playground example to print out the type of the data:
fmt.Printf("%T\n", dat["num"])
If you want to have this be more explicit, you could try changing the type of dat
from map[string]interface{}
to map[string]float64
.