将Marshall MAP转换为JSON。

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

Marshall MAP to JSON

问题

我正在开始从Python转向Go语言的过程中,我正在努力理解数据类型。我需要将一个map转换为以下JSON格式,但我不太确定我的map应该如何构造。

这是我尝试过的代码,但对我来说不起作用。

data := map[string]string{"Offset": "0", "Properties": map[string]string{"key": "Type", "value": "User"}, "Category": "all", "Locations": map[string]string{}, "Accounts": "100"}
data_json, _ := json.Marshal(data)
fmt.Println(string(data_json))

期望的结果:

{
  "Locations": [],
  "Dates": [],
  "Properties": [
    {
      "key": "Type",
      "value": "User"
    }
  ],
  "Category": "all",
  "Accounts": [],
  "Offset": 0,
  "Limit": 100
}
英文:

I'm in the process of getting started with moving from Python to GoLang and I'm trying to get my head around datatype. I need to marshall a map to the following JSON but I'm not quite sure how my map should be constructed.

This is what I've tried but its not working for me.

data := map[string]string{"Offset": "0", "Properties": map[string]string{"key": "Type", "value": "User"}, "Category": "all", "Locations": map[string]string{}, "Accounts": "100" }
data_json, _ := json.Marshal(data)
fmt.Println(string(data_json))

Desired Result:

{
"Locations": [],
"Dates": [],
"Properties": [
  {
    "key": "Type",
    "value": "User"
  }
 ],
 "Category": "all",
 "Accounts": [],
 "Offset": 0,
 "Limit": 100
}

答案1

得分: 7

问题在于你声称要编写一个字符串到字符串的映射(键是字符串且值是字符串)。但是你有一个键/值对:"Properties": map[string]string{"key": "Type", "value": "User"},而该值不是字符串,而是另一个映射。如果你将数据定义为字符串到接口的映射,它应该可以工作。代码应该如下所示:

data := map[string]interface{}{"Offset": "0", "Properties": map[string]string{"key": "Type", "value": "User"}, "Category": "all", "Locations": map[string]string{}, "Accounts": "100"}

这里有一个可工作的示例:
http://play.golang.org/p/HjHH463J_r

如果你不确定接口是什么以及为什么它们可以工作,文档中有很好的解释。

英文:

The issue is that you're claiming to write a map of strings to strings (key is a string AND value is a string). But you have the key/value pair: "Properties": map[string]string{"key": "Type", "value": "User"}, and that value is not a string, its another map. If you define the data as a map of strings to interfaces, it should work. That would look more like this:

data := map[string]interface{}{"Offset": "0", "Properties": map[string]string{"key": "Type", "value": "User"}, "Category": "all", "Locations": map[string]string{}, "Accounts": "100" }

Here is a working example:
http://play.golang.org/p/HjHH463J_r

If you're unsure what interfaces are and why they work, the documentation explains it pretty well.

huangapple
  • 本文由 发表于 2014年12月18日 04:05:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/27533921.html
匿名

发表评论

匿名网友

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

确定