简体   繁体   English

马歇尔MAP到JSON

[英]Marshall MAP to JSON

I'm in the process of getting started with moving from Python to GoLang and I'm trying to get my head around datatype. 我正在开始从Python转到GoLang的过程中,而且我正在设法弄清数据类型。 I need to marshall a map to the following JSON but I'm not quite sure how my map should be constructed. 我需要将地图编组到以下JSON,但我不确定如何构造地图。

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
}

The issue is that you're claiming to write a map of strings to strings (key is a string AND value is a string). 问题是您声称要写一个字符串到字符串的映射(key是一个字符串,value是一个字符串)。 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. 但是您具有键/值对: "Properties": map[string]string{"key": "Type", "value": "User"} ,并且该值不是字符串,而是另一个映射。 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 这是一个工作示例: http : //play.golang.org/p/HjHH463J_r

If you're unsure what interfaces are and why they work, the documentation explains it pretty well. 如果您不确定什么是接口以及它们为什么起作用,那么文档将对它进行很好的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM