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

标签 json go types

我是 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/

相关文章:

javascript - 设计: One AJAX Call or multiple AJAX calls to get list of details

python - 如何使用 python 将列表中的信息填充到多个 JSON 对象中?

php - 如何使用 `vis.js`显示JSON数据

java - 为什么Java和Go的gzip会得到不同的结果?

Typescript:映射类型,使除所选属性之外的每个属性均为只读

c# - 使用 LINQ/JavaScriptSerializer 创建 JSON 对象而不是数组

go - Gmail API : Trashing first email seems to remove entire thread

go - 限制来自 channel 的已处理消息的数量

javascript - 在 TypeScript 中使用符号作为对象键类型

haskell - Haskell中的实际类型与预期类型错误