Home >Backend Development >Golang >How Can I Differentiate Between Empty and Missing Values When Unmarshaling JSON in Go?

How Can I Differentiate Between Empty and Missing Values When Unmarshaling JSON in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 09:40:15280browse

How Can I Differentiate Between Empty and Missing Values When Unmarshaling JSON in Go?

Discerning Void and Unspecified Values in Go Unmarshaling

When unmarshaling JSON data into Go structs, it can be difficult to distinguish between empty and missing values. This is particularly important when you want to handle these values differently in your program.

Consider the following example:

import (
    "encoding/json"
    "fmt"
)

type Category struct {
    Name        string
    Description string
}

var categories []Category

jsonBlob := []byte(`[
    {"Name": "A", "Description": "Monotremata"},
    {"Name": "B"},
    {"Name": "C", "Description": ""}
]`)

err := json.Unmarshal(jsonBlob, &categories)
if err != nil {
    fmt.Println("error:", err)
}
fmt.Printf("%+v", categories)

In this example, the Description field of category B is empty, while the Description field of category C is not specified in the JSON. The output is:

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

As you can see, it is not possible to distinguish between these two cases.

Solution

You can differentiate between empty and missing values by changing the field type to be a pointer. If the value is present in JSON with an empty string value, it will be set to a pointer that points to an empty string. If it is not present in JSON, it will be left nil.

type Category struct {
    Name        string
    Description *string
}

With this modification, the output becomes:

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

Now, you can use the nil value to identify missing fields and handle them accordingly.

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

Statement:
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