回答

收藏

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

技术问答 技术问答 394 人阅读 | 0 人回复 | 2023-09-12

我有以下 JSON
- G0 c3 m0 u0 M$ [1 O3 u2 |! i
    {"a":1,"b":2,"?":1,"??":1}
    3 ^- J% w  H3 L+ {% b8 X# P9 F
我知道它有a”和“b字段,但我不知道其他字段的名字。所以我想用以下类型来解组它:
) `; [! [; w$ N/ 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.}/ R; Q" p( Y8 [! U% S: B/ d5 o
我怎么做?5 [, t( a) W1 M' k
                                                               
7 R- W" M& R( b* K- @; n" V    解决方案:                                                               
; g0 Q8 v9 X- E1 I+ p                                                                解组两次一种选择是解组两次:一次进入一种值,Foo一次进入一个类型的值map[string]interface并删除键"a"和"b":2 B  s0 Y8 z6 ^4 d" f8 x
    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)}, E6 i5 \" K" W6 C3 N0 J
输出(在Go Playground上试试):
- ?  U! @+ _4 D* y9 f
    {A:1 B:2 X:map[x:1 y:1]}& Y) J6 ?2 E+ l3 a) x0 s
手动解组一次另一种选择是将一次解组到 anmap[string]interface{}并手动处理Foo.A和Foo.B字段:
$ m. f; |3 H, U4 J
    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)}( H& [/ J9 d* D) v
输出相同(Go Playground):
$ i& ]1 P4 g3 ^5 k+ X& A
    {A:1 B:2 X:map[x:1 y:1]}* Q! z; W, U1 `2 m1 Q: U  e8 f+ A: E
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则