在Golang中,当对一个空的map进行JSON编码时,会返回{}。

huangapple go评论80阅读模式
英文:

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),
}

https://play.golang.org/p/91vZtJeot3

huangapple
  • 本文由 发表于 2015年7月30日 10:55:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/31714469.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定