"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Differentiate Between Void and Unspecified Fields When Unmarshaling JSON in Go?

How Can I Differentiate Between Void and Unspecified Fields When Unmarshaling JSON in Go?

Posted on 2025-03-23
Browse:177

How Can I Differentiate Between Void and Unspecified Fields When Unmarshaling JSON in Go?

Recognizing Void and Unspecified Fields during JSON Unmarshaling in Go

In JSON, it can be challenging to differentiate between void values and unspecified fields when unmarshaling data into Go structures.

For example, consider the following JSON:

[
  {"Name": "A", "Description": "Monotremata"},
  {"Name": "B"},
  {"Name": "C", "Description": ""}
]

If we define a Go structure like this:

type Category struct {
  Name        string
  Description string
}

and unmarshal the JSON into a slice of Category instances, we get the following output:

[{Name:A Description:Monotremata} {Name:B Description:} {Name:C Description:}]

Notice that the Description field of B is an empty string, while the Description field of C is completely omitted from the JSON. In both cases, the Description field is set to an empty string in the Go representation.

To differentiate between these cases, one approach is to use pointers for optional fields. By changing the type of Description to a pointer, we can distinguish between an empty string value and a nil value (indicating an unspecified field):

type Category struct {
  Name        string
  Description *string
}

When we unmarshal the JSON into this modified structure, we get the following output:

[{Name:A Description:0x1050c150} {Name:B Description:} {Name:C Description:0x1050c158}]

As you can see, the Description field of B is now nil, while the Description field of C is a pointer to an empty string (indicated by the hexadecimal memory address). This allows us to identify unspecified fields and handle them accordingly in our program.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3