Return empty list instead of null

邮差的信 提交于 2020-12-25 05:27:32

问题


I want to change my current function to return empty JSON list, currently it returns nil.

This is my current code:

func (s *Service) projectsGet(c *gin.Context) {
    var projects []*models.Project

    user := getUser(c)
    pag := models.NewPagination(c)

    ps, err := s.db.ProjectsGet(user.ID, &pag)
    if err != nil {
        apiError(c, http.StatusInternalServerError, err)
        return
    }

    projects = ps
    c.JSON(http.StatusOK, projects)
}

I want it to return [], how I can do it?


回答1:


A nil slice encodes to a null JSON object. This is documented at json.Marshal():

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

If you want a non-null empty JSON array, use a non-nil empty Go slice.

See this example:

type Project struct {
    Name string `json:"name"`
}

enc := json.NewEncoder(os.Stdout)

var ps []*Project
enc.Encode(ps)

ps = []*Project{}
enc.Encode(ps)

Output (try it on the Go Playground):

null
[]

So in your case make sure projects is not nil, for example:

projects = ps
if projects == nil {
    projects = []*models.Project{}
}



回答2:


Another way to handle this is to check if the slice is nil and initialize it:

projects = ps
if projects == nil {
    projects = make([]*models.Project, 0)
}

This can be tedious if you have several structs and structs with arrays. To handle those, you can create custom marshalers or dynamically inspect fields.

Source: Arrays and JSON in Go



来源:https://stackoverflow.com/questions/55063756/return-empty-list-instead-of-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!