5

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 Answer 1

17

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

Sign up to request clarification or add additional context in comments.

1 Comment

map[string]string{} also can be used

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.