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

How to Specify Default Values When Parsing JSON in Go?

Mary-Kate Olsen
Release: 2024-12-10 16:24:14
Original
356 people have browsed it

How to Specify Default Values When Parsing JSON in Go?

Specifying Default Values in JSON Parsing with Go

When parsing JSON data into a Go struct, it is often desirable to specify default values for fields that are not present in the JSON. The built-in encoding/json package provides a straightforward mechanism to achieve this.

When calling json.Unmarshal, instead of providing an empty struct, you can provide one with default values. Fields not present in the JSON will retain their default values after unmarshalling.

For example, consider the following struct:

type Test struct {
    A string
    B string
    C string
}
Copy after login

With default values of "a", "b", and "c" for A, B, and C respectively, parsing the JSON below would return a struct with the specified default values:

{"A": "1", "C": "3"}
Copy after login
var example []byte = []byte(`{"A": "1", "C": "3"}`)

out := Test{
    A: "default a",
    B: "default b",
    // default for C will be "", the empty value for a string
}
err := json.Unmarshal(example, &out)
if err != nil {
    panic(err)
}
fmt.Printf("%+v", out)
Copy after login

This code would output:

{A:1 B:default b C:3}
Copy after login

As demonstrated, json.Unmarshal overwrites values specified in the JSON, while leaving unspecified fields with their default values. This technique provides a convenient way to handle missing or incomplete JSON data when parsing into structs.

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