gpt4 book ai didi

go - 向浏览器发送 `null` 而不是 `{}`

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:29 25 4
gpt4 key购买 nike

如果我这样做,我希望能够将 null 作为 JSON 发送到浏览器:

json.NewEncoder(w).Encode(nil)

然后 null 将被浏览器接收。然而在这种情况下:

var nearby map[string]Nearby

// ...

func GetOne(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
item := nearby[params["id"]] // item could be nil?
json.NewEncoder(w).Encode(item)
}

如果 map 中不存在任何内容,则浏览器将接收 {} 而不是 null...有什么方法可以发送 null 如果键不在 map 中?

最佳答案

如问题评论中所示,映射值是一个结构。结构不能具有值 nil

如果意图是在映射中没有值时写入 null,则在这种情况下显式写入 null:

item, ok := nearby[params["id"]]
if ok {
json.NewEncoder(w).Encode(item)
} else {
io.WriteString(w, "null")
// Can also use json.NewEncoder(w).Encode(nil), but that involves more machinery.
}

关于go - 向浏览器发送 `null` 而不是 `{}`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52960428/

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