dqlm80253 2018-06-22 12:53
浏览 159

解组动态JSON,忽略已知字段

I am trying to unmarshal JSON of the following format:

{
  "fixedString": {
    "uselessStuff": {},
    "alsoUseless": {},

    "dynamicField": [
      { "name": "jack" }
    ],
    "dynamicToo": [
      { "name": "jill" }
    ]
  }
}

I would like to drop the fields "uselessStuff" and "alsoUseless", and get everything else. The other keys are user-defined and can take any value.

I can remove the fields I don't want using a custom UnmarshalJSON (based on this answer), but I have a feeling that this is unnecessarily complicated:

package main

import (
    "encoding/json"
    "fmt"
)

type Response struct {
    Things map[string]interface{} `json:"fixedString"`
}

type _R Response

func (f *Response) UnmarshalJSON(bs []byte) (err error) {
    foo := _R{}

    if err = json.Unmarshal(bs, &foo); err == nil {
        *f = Response(foo)
    }

    delete(f.Things, "uselessStuff")
    delete(f.Things, "alsoUseless")

    return err
}

func main() {
    j := []byte(`{ "fixedString": { "uselessStuff": {}, "alsoUseless": {}, "dynamicField": [ { "name": "jack" } ], "dynamicToo": [ { "name": "jill" } ] } }`)

    var r Response
    err := json.Unmarshal(j, &r)
    if err != nil {
        panic(err.Error())
    }

    for x, y := range r.Things {
        fmt.Println(x, y)
    }
}

Is there a way to ignore those two keys using annotations, rather than deleting them in a custom UnmarshalJSON function (and having to add the extra type alias _R to avoid a stack overflow)?

  • 写回答

1条回答 默认 最新

  • duanbing2963 2018-06-22 19:09
    关注

    You could remove your "uselessStuff" and "alsoUseless" from the map and use them as unexported (lowercase) fields in your struct. Most likely not interface{}

    json package ignores unexported fields

    type Response struct {
        Things map[string]interface{} `json:"fixedString"`
        uselessStuff interface{}
        alsoUseless interface{}
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动