我有以下 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.
}
我怎么做?
原文由 Abyx 发布,翻译遵循 CC BY-SA 4.0 许可协议
解组两次
One option is to unmarshal twice: once into a value of type
Foo
and once into a value of typemap[string]interface{}
and removing the keys"a"
and"b"
:输出(在 Go Playground 上尝试):
解组一次和手动处理
另一种选择是将一次解组为
map[string]interface{}
并手动处理Foo.A
和Foo.B
字段:输出相同( Go Playground ):