How to not marshal an empty struct into JSON with Go?

前端 未结 4 2111
一个人的身影
一个人的身影 2020-12-04 15:22

I have a struct like this:

type Result struct {
    Data       MyStruct  `json:\"data,omitempty\"`
    Status     string    `json:\"status,omitempty\"`
    R         


        
4条回答
  •  情话喂你
    2020-12-04 15:42

    There is an outstanding Golang proposal for this feature which has been active for over 4 years, so at this point, it is safe to assume that it will not make it into the standard library anytime soon. As @Matt pointed out, the traditional approach is to convert the structs to pointers-to-structs. If this approach is infeasible (or impractical), then an alternative is to use an alternate json encoder which does support omitting zero value structs.

    I created a mirror of the Golang json library (clarketm/json) with added support for omitting zero value structs when the omitempty tag is applied. This library detects zeroness in a similar manner to the popular YAML encoder go-yaml by recursively checking the public struct fields.

    e.g.

    $ go get -u "github.com/clarketm/json"
    
    import (
        "fmt"
        "github.com/clarketm/json" // drop-in replacement for `encoding/json`
    )
    
    type Result struct {
        Data   MyStruct `json:"data,omitempty"`
        Status string   `json:"status,omitempty"`
        Reason string   `json:"reason,omitempty"`
    }
    
    j, _ := json.Marshal(&Result{
        Status: "204",
        Reason: "No Content",
    })
    
    fmt.Println(string(j))
    
    // Note: `data` is omitted from the resultant json.
    {
      "status": "204"
      "reason": "No Content"
    }
    

提交回复
热议问题