dth20986 2015-07-30 02:55
浏览 173
已采纳

golang 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条回答 默认 最新

  • douyimiao1993 2015-07-30 03:05
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?