Return empty list instead of null

后端 未结 2 1363
南旧
南旧 2021-01-07 12:58

I want to change my current function to return empty JSON list, currently it returns nil.

This is my current code:

func (s *Service) pro         


        
相关标签:
2条回答
  • 2021-01-07 13:50

    Another way to handle this is to check if the slice is nil and initialize it:

    projects = ps
    if projects == nil {
        projects = make([]*models.Project, 0)
    }
    

    This can be tedious if you have several structs and structs with arrays. To handle those, you can create custom marshalers or dynamically inspect fields.

    Source: Arrays and JSON in Go

    0 讨论(0)
  • 2021-01-07 13:54

    A nil slice encodes to a null JSON object. This is documented at json.Marshal():

    Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

    If you want a non-null empty JSON array, use a non-nil empty Go slice.

    See this example:

    type Project struct {
        Name string `json:"name"`
    }
    
    enc := json.NewEncoder(os.Stdout)
    
    var ps []*Project
    enc.Encode(ps)
    
    ps = []*Project{}
    enc.Encode(ps)
    

    Output (try it on the Go Playground):

    null
    []
    

    So in your case make sure projects is not nil, for example:

    projects = ps
    if projects == nil {
        projects = []*models.Project{}
    }
    
    0 讨论(0)
提交回复
热议问题