Search code examples
jsonapirestgomux

Omit struct field in JSON response


I have a struct with some fields as follows:

type Test struct {
    ID        int          `json:"id"`
    Active    bool         `json:"active"`
    Object    []obj.Object `json:"objects"`
}

Then some handler functions that encode Test objects to JSON as a response, but in one of the functions, I want to omit the last field "objects" from the response. I know json:"-" omits it but problem is I need that field for the others functions.

The way I encode the object to JSON is using this method:

 json.NewEncoder(w).Encode(t)

Is there a way I can achieve that? Thanks in advance!


Solution

  • You can use omitempty tag with the struct of pointers. In this case, If the pointers are nil, the fields won't be Marshalled.(https://play.golang.org/p/7DihRGmW0jZ) For Example

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Test struct {
            ID          *int          `json:"id,omitempty"`
            Active      *bool         `json:"active,omitempty"`
            Object      *interface{}  `json:"objects,omitempty"`
    }
    
    func main() {
        var result Test
        id:= 1
        active := true
    
        result.ID = &id
        result.Active = &active
        
        b, err := json.Marshal(result)
        if err != nil {
            panic(err)
        }
        fmt.Printf("%s\n", b)
    }