Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang json encoding return {} for an empty map

Tags:

json

go

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. :/

like image 906
rybit Avatar asked Dec 08 '22 02:12

rybit


1 Answers

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

like image 95
Tim Cooper Avatar answered Dec 11 '22 07:12

Tim Cooper