从字节中解码JSON数据并将浮点值更改为整数。

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

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(&quot;%T\n&quot;, dat[&quot;num&quot;])

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.

huangapple
  • 本文由 发表于 2022年11月14日 14:21:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/74427629.html
匿名

发表评论

匿名网友

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

确定