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条)

报告相同问题?

悬赏问题

  • ¥20 怎么在stm32门禁成品上增加记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 解riccati方程组