json - 即使存在值,Go map 也会返回 nil 值

标签 json dictionary go null

假设下面的 answers 是从 JSON 字符串解码的 map[string]interface{}

if baths, ok := answers["bathrooms"]; ok {
  bathsFloat := baths.(float64)
}

不知何故,我对 接口(interface)转换感到 panic :interface {} 是 nil,不是 float64。当存在检查为真时,这怎么可能?

最佳答案

ok 仅告诉键是否在映射中,与其相关联的值是否为 nil(或通常他值类型的零值)或或不是另一回事。

看这个例子:

answers := map[string]interface{}{
    "isnil":  nil,
    "notnil": 1.15,
}

if v, ok := answers["isnil"]; ok {
    fmt.Printf("Value: %v, type: %T\n", v, v)
}
if v, ok := answers["notnil"]; ok {
    fmt.Printf("Value: %v, type: %T\n", v, v)
}

输出(在 Go Playground 上尝试):

Value: <nil>, type: <nil>
Value: 1.15, type: float64

如果 answers 是 JSON 解码的结果,那么如果源中的值是 JSON ,则与其中的键关联的值将为 nil

看这个例子:

var m map[string]interface{}

err := json.Unmarshal([]byte(`{"isnil":null,"notnil":1.15}`), &m)
if err != nil {
    panic(err)
}
fmt.Println(m)

输出(在 Go Playground 上尝试):

map[notnil:1.15 isnil:<nil>]

关于json - 即使存在值,Go map 也会返回 nil 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52634800/

相关文章:

jquery - 我需要一个方便的 jQuery 工具(插件)来处理 map

runtime - GOMAXPROCS 默认值是多少?

json - Mongoose:将 $in 运算符与 JSON 对象一起使用

java - 类属性的多种类型

css - 通用树数据结构可视化编辑器

c# - 简化构建字典

php - 如何获取给定结构中的 json 输出?

python - 是否有与 Ruby 符号等效的 Python?

Golang并发,批量处理元素

sorting - golang排序 slice 升序或降序