英文:
Decoding JSON data from bytes changing float value to int
问题
以下是将字节数组中的JSON数据解组为结构体,并将浮点数类型的值更改为整数类型的代码。
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)
}
这是Playground链接:https://go.dev/play/p/60YNkhIUABU
有没有办法保持类型不变?
英文:
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?
答案1
得分: 5
解码后的数字已经是 float64
类型。你可以通过在示例代码的末尾添加一行来打印数据类型来验证:
fmt.Printf("%T\n", dat["num"])
如果你想更明确一些,可以尝试将 dat
的类型从 map[string]interface{}
改为 map[string]float64
。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论