Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

go

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 [].

like image 262
praks5432 Avatar asked May 22 '17 18:05

praks5432


People also ask

Can JSON have empty array?

JSON data has the concept of null and empty arrays and objects.

What's null in JSON?

Objects with no value are represented as null.

How check JSON array is empty or not in C#?

IsSuccessStatusCode && instituteDetails. Length>2) and if(createModel. Count()>0) worked fine if you getting empty jsonstring and model .

How do I check if a JSON array is empty in typescript?

We can also explicitly check if the array is empty or not. if (arr. length === 0) { console. log("Array is empty!") }


1 Answers

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)

like image 96
praks5432 Avatar answered Nov 15 '22 04:11

praks5432