简体   繁体   中英

Embedded JSON struct

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?

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

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, ie "Name" should be "name" .

Also, the search for [go] embedded json turned up questions like this ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM