英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论