Home >Backend Development >Golang >How to Set Default Values When Parsing JSON in Go?

How to Set Default Values When Parsing JSON in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-14 11:01:12875browse

How to Set Default Values When Parsing JSON in Go?

Default Value Specification in JSON Parsing with Go

When parsing JSON data in Go using the encoding/json package, you may encounter the need to assign default values to fields that are absent in the input.

Approach Using the encoding/json Package

Yes, the built-in encoding/json package allows you to specify default values. Instead of initializing an empty struct for JSON unmarshaling, you can create a struct with default values and pass it to the unmarshal function.

Example:

type Test struct {
    A string
    B string
    C string
}

func main() {
    var example []byte = []byte(`{"A": "1", "C": "3"}`)

    out := Test{
        A: "default a",
        B: "default b",
    }

    if err := json.Unmarshal(example, &out); err != nil {
        panic(err)
    }

    fmt.Printf("%+v", out)
}

In this example, the values for A and B are specified as "default a" and "default b", respectively. When unmarshalling the JSON, it modifies only the values present in the input (A and C), leaving the others unchanged.

Output:

{A:1 B:default b C:3}

The above is the detailed content of How to Set Default Values When Parsing 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