praks5432
praks5432

Reputation: 7792

Why does json encoding an empty array in code return null?

So I have a types like this

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

Now, I have a handler that does something like this

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)
    }
}

This works fine if there are actual rows, but when encoding an empty array textTagRelationships, in my response in the chrome console I get a null. Why is this happening? It looks like textTagRelationships is actually a [] and so I would have expected the encoding to encode a [] and my response to have a [].

Upvotes: 9

Views: 5505

Answers (1)

praks5432
praks5432

Reputation: 7792

It looks like this is a gotcha in Go.

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

The solution around this is to not rely on the default init behaviour and actually do a make.

var textTagRelationships TextTagRelationships = make(TextTagRelationships, 0)

Upvotes: 13

Related Questions