2015-05-25 20:18
浏览 2.1k


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 {
    A string
    B string
    C string

The default values for A, B, and C, are "a", "b", and "c" respectively. This means that when I parse the json:

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

I want to get the struct:

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

Is this possible using the built-in package encoding/json? Otherwise, is there any Go library that has this functionality?

图片转代码服务由CSDN问答提供 功能建议

我想在Go中解析JSON对象,但想为未给出的字段指定默认值。 例如,我具有结构类型:


A,B和C的默认值分别为“ a”,“ b”和“ c”。 这意味着当我解析json时:

  {“ A”:“ 1”,“ C”:3} 


  Test {A:“ 1”,B:“ b”,C:“ 3”} 

使用内置包 encoding / json 是否可以? 否则,是否有任何具有此功能的Go库?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dqpciw9742 2015-05-25 20:18

    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 {
    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.

    打赏 评论
  • doutangliang7769 2016-12-12 14:23

    In case u have a list or map of Test structs the accepted answer is not possible anymore but it can easily be extended with a UnmarshalJSON method:

    func (t *Test) UnmarshalJSON(data []byte) error {
      type testAlias Test
      test := &testAlias{
        B: "default B",
      _ = json.Unmarshal(data, test)
      *t = Test(*test)
      return nil

    The testAlias is needed to prevent recursive calls to UnmarshalJSON. This works because a new type has no methods defined.

    打赏 评论

相关推荐 更多相似问题