duanpao4522 2016-08-23 09:18
浏览 99
已采纳

解码map和array json

External API returns empty array if no items:

{"items":[]}

...or map with items:

{"items":{"1": {...}, "2": {...}}}

How can I decode both of them? I tried using this struct:

var response struct {
    Items map[string]Item
    Array []Item `json:"items"`
}

But it doesn't work.

UPDATE: Best if both (array and object) will produce a map[string]Item (empty and filled)

  • 写回答

2条回答 默认 最新

  • doutan8775 2016-08-23 14:50
    关注

    If you need to unmarshall to a variable type, the easiest way is to unmarshal into a map[string]interface{} and type-assert (or in this case, type-switch) your way out.

    func Unmarshal(data []byte) (map[string]Item, error) {
        var d struct {
            Items interface{} `json:"items"`
        }
        if err := json.Unmarshal(data, &d); err != nil {
            return nil, err
        }
        switch dv := d.Items.(type) {
        case []interface{}:
            if len(dv) == 0 {
                return nil, nil
            }
        case map[string]interface{}:
            m := make(map[string]Item)
            for k, v := range dv {
                m[k] = Item(v)
            }
            return m, nil
        }
        // fallthrough return if different type, or non-empty array
        // Could have put this in a default case, but this catches non-empty arrays too
        return nil, fmt.Errorf("unexpected type in json")
    }
    

    Here's an example showing it works for both of your provided examples: https://play.golang.org/p/c0oZX2-xpN

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

报告相同问题?

悬赏问题

  • ¥15 无源定位系统的时差估计误差标准差
  • ¥15 请问这个代码哪里有问题啊
  • ¥20 python--version在命令端输入结果Python is not defined怎么办?还有pip不是exe格式是不是没安装成功?
  • ¥15 通过GaussianView进行结构微调消除虚频
  • ¥15 调用transformers库
  • ¥15 由于导出的数据名字中带有/,导致Matlab打不开,怎么办?
  • ¥15 新硬盘安装的程序总是崩溃,提示遇到错误
  • ¥15 openpcdet自制数据集评估bev精度和3d精度相同
  • ¥15 excel 上下按钮 显示行
  • ¥20 云卓h12pro 数传问题