为什么json在代码中编码一个空数组会返回null?

时间:2017-05-22 18:30:58

标签: json go

所以我有类似这样的类型

type TextTagRelationship struct {
  Id int64 `json:"id"`
  TagId int64 `json:"tag_id"`
  TaggedText string `json:"tagged_text"`
  TagName string `json:"tag_name"`
  PageNumber int64 `json:"page_number"`
  Color string `json:"color"`
}

type TextTagRelationships []TextTagRelationship

现在,我有一个像这样的事情的处理程序

func getTaggedTextForPage(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    pageNumber, err := strconv.ParseInt(vars["pageNumber"], 10, 64)
    check(err)
    defer r.Body.Close()
    rows, err := db.Query("SELECT * from tagged_text WHERE page_number = ?", pageNumber)
    check(err)
    var textTagRelationships []TextTagRelationship
    var textTagRelationship TextTagRelationship
    for rows.Next() {
        //execute sql code here
        textTagRelationships = append(textTagRelationships, textTagRelationship)
    }


    if err := json.NewEncoder(w).Encode(textTagRelationships); err != nil {
        check(err)
    }
}

如果有实际的行,这可以正常工作,但是当编码空数组textTagRelationships时,在Chrome控制台的响应中,我得到null。为什么会这样?看起来textTagRelationships实际上是[],因此我希望编码能够对[]进行编码,而我的回复则为[]

1 个答案:

答案 0 :(得分:2)

看起来这是Go中的陷阱。

https://danott.co/posts/json-marshalling-empty-slices-to-empty-arrays-in-go.html

解决这个问题的方法是不依赖于默认的初始化行为,而是实际执行make

var textTagRelationships TextTagRelationships = make(TextTagRelationships, 0)