【发布时间】:2021-01-02 20:55:32
【问题描述】:
我是 Golang 的新手。我必须在 Golang 中对 map[string]interface{} 进行字符串化,就像在 javascript 中对 JSON.stringify 进行字符串化一样。在 javascript 键中,当你执行 JSON.stringify 时,它们的值 undefined 会被省略,而当我在 Golang 中为 nil 值执行 json.Marshal 时,我想要同样的事情。例如在javascript中
var activity = {"isvalid": true, "value": {"prop": undefined}, "prop": undefined}
console.log(JSON.stringify(activity))
// Output: {"isvalid":true,"value":{}}
但如果我这样做,在 Golang 中
activity := map[string]interface{}{
"isvalid": true,
"value": map[string]interface{}{"prop": nil},
"prop": nil,
}
jsonStr, _ := json.Marshal(activity)
fmt.Println(string(jsonStr))
// output: {"isvalid":true,"prop":null,"value":{"prop":null}}
https://play.golang.org/p/dvmz32phdNU
输出存在差异,有什么好方法可以让 Golang 中的输出与 Javascript 中的输出相同?
编辑:
该用例涉及从map[string]interface{} 类型的各种来源获取数据,并且键可以是任意的,因此将其转换为结构对我来说不是一种选择。
【问题讨论】:
-
因为 Go 没有“未定义”的概念:不,你不能做你想做的事。
-
使用带有省略标签选项的结构。 play.golang.org/p/l99KEcjU2az
-
如果不能使用 struct,递归查找 nil 并删除那些键。
标签: javascript json go