Dealing with missing fields when decoding
There are several use cases where developers have to deal with sparse JSON data that does not include all data fields. For instance, a partial update API call may accept a JSON object that contains only those fields that should be updated, without modifying any unspecified data field. In such cases, it becomes important to identify which fields were provided. Then there are use cases where it is appropriate to assume default values for missing fields.
How to do it...
If you want to determine which fields are specified in a JSON input, use pointer fields. Any fields missing in the input will remain as nil
.
To provide default values for missing fields, initialize those fields to their default values before unmarshaling:
type APIRequest struct { // If type is not specified, it will be nil Type *string `json:"type"` // There will be a default value...