How to specify default values when parsing JSON in Go

前端 未结 2 1644
囚心锁ツ
囚心锁ツ 2020-12-09 08:16

I want to parse a JSON object in Go, but want to specify default values for fields that are not given. For example, I have the struct type:

type Test struct          


        
2条回答
  •  佛祖请我去吃肉
    2020-12-09 08:34

    This is possible using encoding/json: when calling json.Unmarshal, you do not need to give it an empty struct, you can give it one with default values.

    For your example:

    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)
    

    Running this example in the Go playground returns {A:1 B:default b C:3}.

    As you can see, json.Unmarshal(example, &out) unmarshals the JSON into out, overwriting the values specified in the JSON, but leaving the other fields unchanged.

提交回复
热议问题