2 回答
TA贡献1825条经验 获得超6个赞
要创建 through map 数组JSON,您需要创建一个map作为slice单个 map 而另一个只是单个 map,然后在单个 map 中一个一个地赋值,然后将其附加到 slice of map 中,如下面的代码所示:
package main
import (
"fmt"
"encoding/json"
)
func main(){
id := [5]string{"1","2","3","4","5"}
name := [5]string{"A","B","C","D","E"}
parseData := make([]map[string]interface{}, 0, 0)
for counter,_ := range id {
var singleMap = make(map[string]interface{})
singleMap["id"] = id[counter]
singleMap["name"] = name[counter]
parseData = append(parseData, singleMap)
}
b, _:= json.Marshal(parseData)
fmt.Println(string(b))
}
你也可以在这里测试
它打印JSON
为:
[{"id":"1","name":"A"},
{"id":"2","name":"B"},
{"id":"3","name":"C"},
{"id":"4","name":"D"},
{"id":"5","name":"E"}]
TA贡献1821条经验 获得超4个赞
对我来说,这更像是一组对象。您可以像这样获得所需的输出:
type data struct {
Id string
Name string
}
func main(){
id := [5]string{"1","2","3","4","5"}
name := [5]string{"A","B","C","D","E"}
var parsedData []data
for counter := range id {
parsedData = append(parsedData, data{Name: name[counter], Id: id[counter]})
}
bytes, _ := json.Marshal(parsedData)
fmt.Print(string(bytes))
}
输出应如下所示:
[
{"Id":"1","Name":"A"},
{"Id":"2","Name":"B"},
{"Id":"3","Name":"C"},
{"Id":"4","Name":"D"},
{"Id":"5","Name":"E"}
]
- 2 回答
- 0 关注
- 116 浏览
添加回答
举报