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
Release: 2024-12-04 09:40:15
Original
237 people have browsed it

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)
Copy after login

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:}]
Copy after login

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
}
Copy after login

With this modification, the output becomes:

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

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!

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