Renoa
Renoa

Reputation: 417

How to ignore empty fields when using json.Marshal on an external Go struct?

I have a struct defined in an external package (i.e. I have no control over this struct). When I use json.Marshal to convert it into a json string, the fields that are not set are included as null. How can I marshal it so that the unset fields are ignored? For example:

External struct (I can't modify this!):

type ExternalStruct struct {
    Success bool
    Details *string
}

In my code:

import "external/package/providing/external/struct"
import "encoding/json"
...
result := ExternalStruct{Success: true}
resultJson, _ := json.Marshal(result)
println(string(resultJson))

returns: {"Success": true, "Details": null} but I want: {"Success": true}

I'm looking for a solution that does not rely on knowing the internals of externalStruct, if at all possible, because I have several external structs affected by this, so ideally I would like to have a single piece of code that can marshal them while ignoring any unset fields. Some of the structs have nested structs too.

Upvotes: 1

Views: 372

Answers (1)

Krzysztof Madejski
Krzysztof Madejski

Reputation: 7978

When you want to control the contract (hhow data is marshaled) I'd suggest not relying on external struct that can change without notice. Instead create your own struct and copy the fields.

Upvotes: 2

Related Questions