英文:
How to put data in a struct with Golang?
问题
这是我的代码:
package main
import "fmt"
type Species struct {
Human []Info
Animal []Info
}
type Info struct {
Name string
Number string
}
func main() {
var data Species
data = Species{
Human: []Info{
{Name: "dave", Number: "00001"},
{Name: "jack", Number: "00002"},
{Name: "nate", Number: "00003"},
},
Animal: []Info{
{Name: "ko", Number: "00004"},
{Name: "na", Number: "00005"},
},
}
fmt.Println(data)
}
在代码中的????
处,你可以这样写:
data = Species{
Human: []Info{
{Name: "dave", Number: "00001"},
{Name: "jack", Number: "00002"},
{Name: "nate", Number: "00003"},
},
Animal: []Info{
{Name: "ko", Number: "00004"},
{Name: "na", Number: "00005"},
},
}
这样就可以将数据填充到data
结构体中了。
英文:
Here is my code:
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)
}
I want to see it as json like this:
{
"human":[
{"name":"dave","number":"00001"},
{"name":"jack","number":"00002"},
{"name":"nate","number":"00003"}
],
"animal":[
{"name":"ko","number":"00004"},
{"name":"na","number":"00005"}
]
}
I don't know how to put in data that struct. What do I write on '???' in code?
答案1
得分: 0
使用encoding/json
包可以进行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))
}
你可以在这里找到完整的代码。
英文:
form [json][1] pkg you can encoding and decoding JSON format
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))
}
https://play.golang.org/p/evQto70Z8y
[1]: https://golang.org/pkg/encoding/json/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论