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 [].
JSON data has the concept of null and empty arrays and objects.
Objects with no value are represented as null.
IsSuccessStatusCode && instituteDetails. Length>2) and if(createModel. Count()>0) worked fine if you getting empty jsonstring and model .
We can also explicitly check if the array is empty or not. if (arr. length === 0) { console. log("Array is empty!") }
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With