1

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.

1
  • If you want details included if it's set, you should reexamine your desire to omit details if null. Consistency is a more valuable aspect of a data contract than minimalism Commented Aug 1, 2022 at 1:58

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.