Json 枚举切片条目
如果我有这个输出Json 枚举切片条目,json,go,Json,Go,如果我有这个输出 Stuff { "Items": [ { "title": "test1", "id": "1", }, { "title": "test", "id": "2", }, ], "total": 19 }, }
Stuff {
"Items": [
{
"title": "test1",
"id": "1",
},
{
"title": "test",
"id": "2",
},
],
"total": 19
},
}
但我希望这样:
stuff {
"Items": [
1:{
"title": "test1",
"id": "1",
},
2:{
"title": "test",
"id": "2",
},
],
"total": 19
},
}
目前,我的结构是这样构建的:
Stuff struct {
Items []Items `json:"items"`
Total int `json:"total"`
} `json:"stuff"`
type Items struct {
Title string `json:"title"`
ID string `json:"id"`
}
我通过以下方式启动切片:
stuff := make([]Items, 10) // Lets say I have 10 entries
并通过以下方式附加:
Stuff.Items = stuff
Stuff.Total = len(Stuff.Items)
现在我不知道如何计算。因此,对于每个条目,都应该有一个数字,从1到10开始(在本例中)给定您的
内容
和条目
类型声明,下面是一个简单的数据结构及其JSON转储:
s := Stuff{Items: []Items{Items{"test1", "1"}, Items{"test2", "2"}}, Total: 10}
j, err := json.MarshalIndent(s, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(j))
JSON:
相反,要查看您想要什么,没有神奇的json
package调用。您必须创建一个反映所需输出结构的新数据结构
在这种情况下,一张简单的地图可以:
m := make(map[string]Items)
for _, item := range s.Items {
m[item.ID] = item
}
现在,如果您转储此地图,您将得到:
{
"1": {
"title": "test1",
"id": "1"
},
"2": {
"title": "test2",
"id": "2"
}
}
注意,我现在没有用
Stuff
来包装它,因为Stuff
有不同的字段。Go是静态类型的,每个结构只能包含您声明的字段。所需的输出不是有效的JSON。键只能是字符串encoding/json
支持解析和生成有效的json。因此,如果我希望它是“1”:{},“2{},依此类推。我该怎么做?最简单的方法是将其转换为映射,然后封送映射。你试过什么?包括你的代码。你遇到了什么问题?
{
"1": {
"title": "test1",
"id": "1"
},
"2": {
"title": "test2",
"id": "2"
}
}