这是我的代码:
package main
import "fmt"
type Species struct {
Human []Info
Animal []Info
}
type Info struct {
Name string
Number string
}
func main() {
var data Species
data = ????
fmt.Println(data)
}
我希望将其视为json:
{
"human":[
{"name":"dave","number":"00001"},
{"name":"jack","number":"00002"},
{"name":"nate","number":"00003"}
],
"animal":[
{"name":"ko","number":"00004"},
{"name":"na","number":"00005"}
]
}
我不知道如何输入结构数据。我该怎么写' ???'在代码?
答案 0 :(得分:0)
表单json pkg您可以编码和解码JSON格式
package main
import (
"encoding/json"
"fmt"
)
type Species struct {
Human []Info `json:"human"`
Animal []Info `json:"animal"`
}
type Info struct {
Name string `json:"name"`
Number string `json:"number"`
}
func main() {
data := Species{
Human: []Info{
Info{Name: "dave", Number: "00001"},
Info{Name: "jack", Number: "00002"},
},
Animal: []Info{
Info{Name: "ko", Number: "00004"},
Info{Name: "na", Number: "00005"},
},
}
b, err := json.MarshalIndent(data, "", " ")
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(string(b))
}