回答

收藏

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

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

我有以下 JSON
* K) }  ]; |. ]2 ~
    {"a":1,"b":2,"?":1,"??":1}1 f3 ^$ }4 U7 @3 X
我知道它有a”和“b字段,但我不知道其他字段的名字。所以我想用以下类型来解组它:
* ~* s2 x/ Y2 r. O* U' o
    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.}
    # i) Z" n% E8 C( S4 f6 g
我怎么做?3 x* I2 y& Z! x$ k5 U5 _/ s; N
                                                                3 o  \' E/ w6 v; [% r
    解决方案:                                                               
! @; J3 n. C% {( l% B8 J/ ^2 w: m; j& c                                                                解组两次一种选择是解组两次:一次进入一种值,Foo一次进入一个类型的值map[string]interface并删除键"a"和"b":: q) f3 t  Q2 I( o; Y* ]' o
    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)}5 T4 L- |/ g( C7 o! {! T/ b8 I& G: v
输出(在Go Playground上试试):
8 v( t) R/ [  {4 N+ G& H
    {A:1 B:2 X:map[x:1 y:1]}
    ( O; N" o9 n- m# J3 H7 f7 ^% G0 k
手动解组一次另一种选择是将一次解组到 anmap[string]interface{}并手动处理Foo.A和Foo.B字段:& F  ^- w, R5 N) c6 c  P
    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)}7 {( E7 z0 D3 T5 B. S
输出相同(Go Playground):
0 ~) R' b4 P& v$ o6 u; `* P
    {A:1 B:2 X:map[x:1 y:1]}
    + C) v% t% a5 o. E& |! T' t
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则