英文:
golang json encoding return {} for an empty map
问题
我正在尝试让json.Marshal
返回{"map": {}}
而不是{"map":null}
,但是encoding/json
似乎检测到这是一个空映射,并且只返回后者的值。
我尝试过手动初始化映射并使用引用,但都没有得到我想要的输出。你有什么建议吗?
英文:
I am trying to get go to actually return me something like this:
{"map": {}}
not {"map":null}
but the encoding/json seems to detect that this is an empty map and only return the latter value.
type test struct {
MyMap map[string]string `json:"map"`
}
func main() {
testval := test{}
asjson, err := json.Marshal(testval)
fmt.Println(testval)
fmt.Println(string(asjson))
}
The output is like this
{map[]}
{"map":null}
I am looking to get it to be {"map":{}}
suggestions? I have tried to initialize the map manually, and use a reference for it. Neither seems to yield the output I want. :/
答案1
得分: 16
test.MyMap
尚未初始化,因此它是nil
。初始化它将给你所期望的结果:
testval := test{
MyMap: make(map[string]string),
}
https://play.golang.org/p/91vZtJeot3
英文:
test.MyMap
hasn't been initialized, so it is nil
. Initializing it will give you the desired result:
testval := test{
MyMap: make(map[string]string),
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论