-1

My model having following data:

package main

type Subject struct {
    name    string `json:name`
    section int     `json:section`
}

var subjects = map[string][]Subject{
    "1001": []Subject{
        {
            name:    "Phy",
            section: 1,
        },
        {
            name:    "Phy",
            section: 2,
        },
    },
    "1002": []Subject{
        {
            name:    "Chem",
            section: 1,
        },
        {
            name:    "Chem",
            section: 2,
        },
    },
    "1003": []Subject{
        {
            name:    "Math",
            section: 1,
        },
        {
            name:    "Math",
            section: 2,
        },
    },
    "1004": []Subject{
        {
            name:    "Bio",
            section: 1,
        },
        {
            name:    "Bio",
            section: 2,
        },
    },
}

I am creating route as follows:

route.GET("/subjects/:id", func(c *gin.Context) {
    
        id := c.Param("id")
        subjects := subjects[id]

        c.JSON(http.StatusOK, gin.H{
            "StudentID": id,
            "Subject":  subjects,
        })
    })

It tried to call it using postman as : localhost:8080/subjects/1001 but it just shows {} {} instead of array of subject struct's objects.

Output: { "StudentID": "1001", "Subject": [ {}, {} ] }

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Pramod
  • 21
  • 6
  • 2
    You need to export the fields so that the `json` package can encode them e.g. `Name` and `Section` vs `name` and `section`. If you'd like them to be lowercase in the response, you can use a json tag e.g. `Name string \`json: "name"\``. – Gavin Apr 30 '21 at 13:44

1 Answers1

0

This is because your Subject uses lowercase fields name and section and thus will not be serialized.

Changing it to:

type Subject struct {
    Name    string `json:"name"`
    Section int    `json:"section"`
}

Will show the fields:

{
  "StudentID": "1001",
  "Subject": [
    {"name":"Phy","section":1},
    {"name":"Phy","section":2}
  ]
}
ResamVi
  • 86
  • 4
  • The keys in the JSON for the Subject objects will actually be lowercase because of your tags. – Gavin Apr 30 '21 at 13:52
  • You're right. I copied this part from his. Writing it as `json:name` doesn't make it lowercase at all, it seems. I'll edit it to the way it was (supposedly) intended. – ResamVi Apr 30 '21 at 13:57