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

How Can I Set Default Values When Parsing JSON in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 17:12:17541browse

How Can I Set Default Values When Parsing JSON in Go?

Specifying Default Values in JSON Parsing with Go

When parsing JSON objects in Go, it may be necessary to specify default values for fields that are not provided in the input JSON. Consider a struct type with the following fields:

type Test struct {
    A string
    B string
    C string
}

Suppose the desired default values for A, B, and C are "a", "b", and "c", respectively. When parsing the following JSON:

{"A": "1", "C": 3}

the expected struct would be:

Test{A: "1", B: "b", C: "3"}

Using the encoding/json Package

The built-in encoding/json package in Go allows for the specification of default values during JSON parsing. Instead of using an empty struct, provide a struct with the desired default values as follows:

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)

By calling json.Unmarshal(example, &out), the JSON is unmarshaled into the out struct, overwriting the values specified in the JSON. However, the default values for fields not present in the JSON remain unchanged. Running the example returns:

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

Other Go Libraries

If the encoding/json package does not meet specific requirements, there are other Go libraries that provide similar functionality. Consider the following:

  • [xjson](https://github.com/gobuffalo/x/blob/master/xjson/xjson.go) provides a customizable JSON parser that allows for the specification of default values and other options.
  • [eson](https://github.com/sean-/eson) is another JSON parser that supports default values through its default() method.

The above is the detailed content of How Can I 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