Home > Backend Development > Golang > How Can I Differentiate Between Null and Missing JSON Fields in Go?

How Can I Differentiate Between Null and Missing JSON Fields in Go?

Barbara Streisand
Release: 2024-11-30 19:35:12
Original
487 people have browsed it

How Can I Differentiate Between Null and Missing JSON Fields in Go?

Differentiating Null and Non-Existent JSON Fields in Go

When unmarshalling JSON into Go structs, it can be challenging to distinguish between JSON fields that are explicitly set to null and those that are simply not present in the JSON payload. This distinction is crucial in many scenarios, as it affects the semantics of the data and its interpretation.

Go 1.18 Solution

Starting with Go 1.18, a generic Optional struct can be utilized to address this issue:

type Optional[T any] struct {
    Defined bool
    Value   *T
}
Copy after login

This struct implements the UnmarshalJSON interface, allowing it to distinguish defined and undefined values. When unmarshalling a JSON payload, the defined field of the Optional struct will be set to true, regardless of whether the value is null or a valid value.

Example Usage

type Payload struct {
    Field1 Optional[string] `json:"field1"`
    Field2 Optional[bool]   `json:"field2"`
    Field3 Optional[int32]  `json:"field3"`
}
Copy after login

After unmarshalling a JSON payload, the Defined field can be used to determine if a specific field was present in the JSON or not.

Pre-Go 1.18 Solution

For versions of Go prior to 1.18, a custom type can be created to achieve the same result.

type OptionalString struct {
    Defined bool
    Value   *string
}
Copy after login

Similar to the Optional struct in Go 1.18 , this type implements the UnmarshalJSON interface to set the Defined field accordingly.

Example Usage

type Payload struct {
    SomeField1 string         `json:"somefield1"`
    SomeField2 OptionalString `json:"somefield2"`
}
Copy after login

By utilizing this custom type, the Defined field can be inspected to differentiate between null and non-existent fields.

The above is the detailed content of How Can I Differentiate Between Null and Missing JSON Fields in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template