小编典典

使用一些已知和一些未知的字段名称解组 JSON

go

我有以下 JSON

{"a":1, "b":2, "?":1, "??":1}

我知道它有“a”和“b”字段,但我不知道其他字段的名称。所以我想用以下类型解组它:

type Foo struct {
  // Known fields
  A int `json:"a"`
  B int `json:"b"`
  // Unknown fields
  X map[string]interface{} `json:???` // Rest of the fields should go here.
}

我怎么做?


阅读 356

收藏
2021-12-16

共1个答案

小编典典

解组两次

一种选择是解组两次:一次进入一个类型的值,Foo一次进入一个类型的值map[string]interface{}并删除键"a""b"

type Foo struct {
    A int                    `json:"a"`
    B int                    `json:"b"`
    X map[string]interface{} `json:"-"` // Rest of the fields should go here.
}

func main() {
    s := `{"a":1, "b":2, "x":1, "y":1}`
    f := Foo{}
    if err := json.Unmarshal([]byte(s), &f); err != nil {
        panic(err)
    }

    if err := json.Unmarshal([]byte(s), &f.X); err != nil {
        panic(err)
    }
    delete(f.X, "a")
    delete(f.X, "b")

    fmt.Printf("%+v", f)
}

输出(在Go Playground上试试):

{A:1 B:2 X:map[x:1 y:1]}

解组一次和手动处理

另一种选择是将一次解组到 anmap[string]interface{}并手动处理Foo.AFoo.B字段:

type Foo struct {
    A int                    `json:"a"`
    B int                    `json:"b"`
    X map[string]interface{} `json:"-"` // Rest of the fields should go here.
}

func main() {
    s := `{"a":1, "b":2, "x":1, "y":1}`
    f := Foo{}
    if err := json.Unmarshal([]byte(s), &f.X); err != nil {
        panic(err)
    }
    if n, ok := f.X["a"].(float64); ok {
        f.A = int(n)
    }
    if n, ok := f.X["b"].(float64); ok {
        f.B = int(n)
    }
    delete(f.X, "a")
    delete(f.X, "b")

    fmt.Printf("%+v", f)
}

输出相同(Go Playground):

{A:1 B:2 X:map[x:1 y:1]}
2021-12-16