英文:
Golang - convert array / map to JSON
问题
我正在尝试将一个map[]转换为JSON,以便我可以将其作为请求的一部分进行提交。但是我的map[]包含了不同的类型,包括字符串和整数。
我目前的代码如下:
mapD := map[string]string{"deploy_status": "public", "status": "live", "version": 2}
mapB, _ := json.Marshal(mapD)
fmt.Println(string(mapB))
//输出结果
prog.go:17: cannot use 2 (type int) as type string in map value
请问如何使得我可以在同一个map中包含字符串和整数呢?
谢谢。
英文:
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
答案1
得分: 5
使用map[string]interface{}:
mapD := map[string]interface{}{"deploy_status": "public", "status": "live", "version": 2}
英文:
Use map[string]interface{} :
mapD := map[string]interface{}{"deploy_status": "public", "status": "live", "version": 2}
答案2
得分: 1
你正在尝试将一个类型为int
的值用作字符串,但是你的映射被定义为[string]string
。你需要将第一行修改为:
mapD := map[string]string{"deploy_status": "public", "status": "live", "version": "2"}
如果你不知道值的类型,可以使用interface{}
代替。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论