Home > Backend Development > Golang > How to Handle Missing JSON Fields with Default Values in Go?

How to Handle Missing JSON Fields with Default Values in Go?

Patricia Arquette
Release: 2024-12-13 05:54:13
Original
398 people have browsed it

How to Handle Missing JSON Fields with Default Values in Go?

Parsing JSON with Default Values in Go

When parsing JSON in Go and encountering missing or undefined fields, it's often desirable to assign default values to ensure a complete and consistent data representation.

To achieve this using the built-in encoding/json package, avoid passing an empty struct to json.Unmarshal. Instead, initialize the struct with default values. For instance, let's 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 fields A, B, and C, respectively, we can parse the JSON string:

{"A": "1", "C": 3}
Copy after login

into the following struct:

out := Test{
    A: "default a",
    B: "default b",
    // C defaults to the empty value ""
}
Copy after login

By calling json.Unmarshal(example, &out), the JSON is unmarshaled into out, overriding specified fields with their values from the JSON while preserving default values for the remaining fields. The above example would result in {A:1 B:default b C:3}.

This technique offers a straightforward way to handle missing fields in JSON data parsing while maintaining data integrity.

The above is the detailed content of How to Handle Missing JSON Fields with Default Values 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