英文:
Embedded JSON struct
问题
这是我的结构体:
type studentData struct {
Name string `bson:"name"`
Grade int `bson:"Grade"`
}
type student struct {
student []studentData `json:"student"`
}
我需要得到以下的 JSON 结果:
{
"array": [
{
"Name": "ethan",
"Grade": 2
},
{
"Name": "rangga",
"Grade": 2
}
]
}
我从 MongoDB 获取数据,已经尝试搜索,但没有找到我需要的结果,有人可以帮助我吗?
英文:
Here my struct
type studentData struct {
Name string `bson:"name"`
Grade int `bson:"Grade"`
}
type student struct {
student []studentData `json:"student"`
}
I need my JSON result like this
{
"array": [
{
"Name": "ethan",
"Grade": 2
},
{
"Name": "rangga",
"Grade": 2
}
]
}
I get the data from mongoDB, already tried to search but did not found that i need, could someone help me?
答案1
得分: 2
尽管你的JSON没有太多意义,但以下代码将输出你想要的确切JSON:
package main
import (
"encoding/json"
"os"
)
type Student struct {
Name string `json:"name"`
Grade int `json:"Grade"`
}
type Students struct {
Array []Student `json:"array"`
}
func main() {
student1 := Student{
Name: "Josh",
Grade: 2,
}
student2 := Student{
Name: "Sarah",
Grade: 4,
}
students := Students{
Array: []Student{student1, student2},
}
b, err := json.Marshal(students)
if err != nil {
panic(err)
}
os.Stdout.Write(b)
}
在这里尝试代码:https://play.golang.org/p/PcPZOuxJUM
英文:
Although your JSON doesn't make a lot of sense, this will output the exact JSON you want:
package main
import (
"encoding/json"
"os"
)
type Student struct {
Name string `json:"name"`
Grade int `json:"Grade"`
}
type Students struct {
Array []Student `json:"array"`
}
func main() {
student1 := Student{
Name: "Josh",
Grade: 2,
}
student2 := Student{
Name: "Sarah",
Grade: 4,
}
students := Students{
Array: []Student{student1, student2},
}
b, err := json.Marshal(students)
if err != nil {
panic(err)
}
os.Stdout.Write(b)
}
Try the code here https://play.golang.org/p/PcPZOuxJUM
答案2
得分: 0
对于encoding/json
能够对你的结构体进行编组,它需要看到你想要序列化的字段。
在你的情况下,student.student
没有被导出,因此对于encoding/json
来说是不可见的。将其导出即可解决问题:
type student struct {
Student []studentData `json:"student"`
}
顺便提一下:在名为"student"的结构体中,使用除了"Student"之外的其他名称来表示类型为[]studentData
的字段,比如"Grades"或"TranscriptInformation"。
另外,你期望的JSON格式不正确,标识符/键不应该大写,即"Name"
应该是"name"
。
此外,搜索 embedded json
会出现类似这样的问题。
英文:
For encoding/json
to be able to marshal your struct, it needs to see the fields you want it to serialize.
In your case, student.student
is not exported and therefore not visible to encoding/json
. Export it and it works:
type student struct {
Student []studentData `json:"student"`
}
A note on the side: Use something else than "Student" for a field of type []studentData
in a struct named "student". Maybe something like "Grades" or "TranscriptInformation"?
Another note on the side: Your desired JSON is not "right", identifiers/keys should not be capitalized, i.e. "Name"
should be "name"
.
Also, the search for embedded json
turned up questions like this
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论