1 回答
TA贡献1830条经验 获得超9个赞
不需要为狗和猫分别创建json对象。这将导致在编组数据时产生单独的 json 对象。
您尝试的方法基本上是适当且无用的。
方法应该创建一个结果结构,它将 dogs 和 cats 结构作为字段,类型分别作为它们的切片。举个例子:
package main
import (
"fmt"
"encoding/json"
"log"
)
type Result struct{
Dog []Dog
Cat []Cat
}
type Dog struct{
Breed string
Color string
}
type Cat struct {
Breed string
Color string
}
func main(){
dogs := []Dog{
{"Chihuahua", "brown"},
{"Pug", "white"},
}
cats := []Cat{
{"British", "white"},
{"Ragdoll", "gray"},
}
result := Result{
Dog: dogs,
Cat: cats,
}
output, err := json.MarshalIndent(result, "", "\t")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(output))
}
输出:
{
"Dog": [
{
"Breed": "Chihuahua",
"Color": "brown"
},
{
"Breed": "Pug",
"Color": "white"
}
],
"Cat": [
{
"Breed": "British",
"Color": "white"
},
{
"Breed": "Ragdoll",
"Color": "gray"
}
]
}
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报