使用一些已知和一些未知的字段名称解组 JSON [英] Unmarshal JSON with some known, and some unknown field names

查看:31
本文介绍了使用一些已知和一些未知的字段名称解组 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 JSON

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

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

I know that it has the "a" and "b" fields, but I don't know the names of other fields. So I want to unmarshal it in the following type:

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

我该怎么做?

推荐答案

解组两次

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

Unmarshal twice

One option is to unmarshal twice: once into a value of type Foo and once into a value of type map[string]interface{} and removing the keys "a" and "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 上试试):

Output (try it on the Go Playground):

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

解组一次并手动处理

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

Unmarshal once and manual handling

Another option is to unmarshal once into an map[string]interface{} and handle the Foo.A and Foo.B fields manually:

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]}

这篇关于使用一些已知和一些未知的字段名称解组 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆