Golang – 将数组/映射转换为JSON

huangapple go评论96阅读模式
英文:

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}

playground

英文:

Use map[string]interface{} :

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

playground

答案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.

huangapple
  • 本文由 发表于 2016年4月18日 17:17:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/36689892.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定