douyi9447 2016-03-31 00:28
浏览 39
已采纳

解组不一致的JSON

I have JSON (that I cannot control) like this:

{
    "foo1":{
        "a":{
             "up":10,
             "down":5
        }
    },
    "foo2":{
        "a":{
             "up":1,
             "down":1
        }
    },
    "bar":{
        "up":11,
        "down":6
    }
}

"foo1" and "foo2" are dynamic.

How can I properly unmarshal this structure in go?

It would be okay if I could just tell go to not try to deserialize "bar" (the inconsistent property).

  • 写回答

2条回答 默认 最新

  • douan5151 2016-03-31 17:09
    关注

    You said:

    I have JSON (that I cannot control)

    So to what extent you could control? Here I could provide you with some scenario, and hope some of them match your purpose :)

    Remember the general rule first:

    In Golang, if a JSON key failed to find a matched field in struct, it will not be unmarshalled.

    This means, for a key name in a JSON struct, when unmarshalling, it will look for a field in a golang struct at the same level with the same name case-insensitively. If this search failed, this key won't be unmarshalled.

    For example, a key named foo1 will look for a field name foo1 in a golang struct at the same indent level. However it also matches with Foo1 or FoO1, since this matching is case-insensitive.

    Remember, you could use field tag to specify the field name as well. Please take a look at the official page.

    The value of some of the JSON fields are not consistent, and they could be ignored.

    This is the case @gnalck solved in his answer. According to the general rule, if those inconsistent field failed to find a match, they will not be unmarshalled. Therefore, just don't put those inconsistent fields in the struct and you will be fine.

    The value of some of the JSON fields are not consistent, but they could not be ignored.

    In this case, @gnalck failed since those fields could not be ignored. Now a better way is to unmarshal bar into a json.RawMessage, so that you could unmarshal later.

    The keys of the JSON object is undetermined, and their value is undetermined as well.

    In this case, we could unmarshal the whole JSON object into a map[string]json.RawMessage, and unmarshal each fields later. When unmarshalling to a map, you could iterate through the map to get all the fields, and unmarshal them into a proper struct later.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料