Elliot Reeve
Elliot Reeve

Reputation: 941

Golang - convert array / map to JSON

I am trying to convert a map[] to JSON so I can post it as part of a request. But my map[] has various types including strings / ints.

I currently have:

mapD := map[string]string{"deploy_status": "public", "status": "live", "version": 2}
mapB, _ := json.Marshal(mapD)
fmt.Println(string(mapB))

//output
prog.go:17: cannot use 2 (type int) as type string in map value

How do I make it so that I can include strings and ints within the same map?

Thanks

Upvotes: 2

Views: 10952

Answers (2)

fzerorubigd
fzerorubigd

Reputation: 1874

Use map[string]interface{} :

mapD := map[string]interface{}{"deploy_status": "public", "status": "live", "version": 2}

playground

Upvotes: 5

Endre Simo
Endre Simo

Reputation: 11541

You are trying to use a value of type int as a string, but your map is defined as [string]string. You have to modify the first line as:

mapD := map[string]string{"deploy_status": "public", "status": "live", "version": "2"}

If you do not know the type of the values, you can use interface{} instead.

Upvotes: 1

Related Questions