gpt4 book ai didi

json - Go 的 .(type) 在解码 JSON 时做一些意外的事情

转载 作者:IT王子 更新时间:2023-10-29 01:52:15 24 4
gpt4 key购买 nike

我是 RTFMing ,特别是关于解码任意围棋数据的部分。基于该部分,我编写了以下测试程序

var f interface{}

json.Unmarshal(
[]byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`), &f)

m := f.(map[string]interface{})
for k, v := range m {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case int:
fmt.Println(k, "is int", vv)
case []interface{}:
fmt.Println(k, "is an array:")
for i, u := range vv {
fmt.Println(i, u)
}
default:
fmt.Println(k, "is of a type I don't know how to handle")
fmt.Println(" Type Is:", vv)
}
}

也就是说,我声明了一个空接口(interface)类型的变量。根据文档,我

use a type assertion to access f's underlying map[string]interface{}:

然后,我使用 range 对 map 的键/值对执行 for 循环。如果该值是字符串、整数或 []interface,程序会这样说。如果该值是另一种类型(默认情况),程序会说我不知道​​如何处理它。这几乎是手册中的逐字代码。

程序产生以下输出。

Name is string Wednesday
Age is of a type I don't know how to handle
Type Is: 6
Parents is an array:
0 Gomez
1 Morticia

也就是说——它正确地识别了字符串和数组的类型——出于某种原因,似乎解析的 6 的类型不是 int -- 是 6。

所以——我想我的问题是 *为什么 v.(type) 在这里返回实际数字而不是 int 我的问题是为什么这个问题是错误的

最佳答案

JSON 数字是 double float ,因此 go 使用的默认类型是 float64。您可以看到 json.Unmarshal 中列出的默认值文档。

关于json - Go 的 .(type) 在解码 JSON 时做一些意外的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46836641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com