返回空列表,而不是null

kod*_*diu 0 null json go slice

我想更改当前函数以返回空的JSON列表,当前它返回nil

这是我当前的代码:

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)
}
Run Code Online (Sandbox Code Playgroud)

我要它退货[],我该怎么办?

icz*_*cza 5

nil切片编码到一个nullJSON对象。记录在json.Marshal()

数组和切片值编码为JSON数组,除了[] byte编码为base64编码的字符串,而nil slice编码为空JSON值

如果您想要一个非null空的JSON数组,请使用一个非nil空的Go slice。

请参阅以下示例:

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

enc := json.NewEncoder(os.Stdout)

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

ps = []*Project{}
enc.Encode(ps)
Run Code Online (Sandbox Code Playgroud)

输出(在Go Playground上尝试):

null
[]
Run Code Online (Sandbox Code Playgroud)

因此,请确保您projects不是nil,例如:

projects = ps
if projects == nil {
    projects = []*models.Project{}
}
Run Code Online (Sandbox Code Playgroud)