2

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

2 Answers 2

6

Use map[string]interface{} :

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

playground

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

1 Comment

Thanks I was missing the {} before then opening the {} again :)
1

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.

3 Comments

I can't change the int to a string as this would be invalid on the request side so it has to stay an int.
If I do the interface version: mapD := map[string]interface{"deploy_status": "public", "status": "live", "version": 2} mapB, _ := json.Marshal(mapD) fmt.Println(string(mapB)) I get the error of: syntax error: unexpected string literal
Yes, because you're not initializing the interface correctly.You should use map[string]interface{}{...}

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.