doufu2496 2019-08-06 07:11
浏览 36
已采纳

在map [string] interface {}的值上键入switch到[] map [string] interface {}

Problem

I'm facing the issue to remove not required arrays from an json object eg. arrays with only one element which is not an object or array. (No arrays as root of the input)

Example

In:

{"name": [{ "inner": ["test"] }]}

Wanted Out:

{"name": [{ "inner": "test" }]}

Approach

I started with a simple type switch on the values of a parsed map[string]interface{} and recognized that it wont switch to the case []map[string]interface{}. (Given example)

So here is the implementation I came up with. It works for most of the scenarios but not for inner Objects within an array yet.

type jsonMap map[string]interface{}
type jsonMapList []map[string]interface{}

m := jsonMap{}

err := json.Unmarshal(s, &m)
if err != nil {
    panic(err)
}

res := removeFromObject(m)

bytes, err := json.Marshal(res)
if err != nil {
    panic(err)
}
result := string(bytes)
log.Infof("Parse Result: %s", result)

func removeFromObject(in jsonMap) jsonMap {
    res := jsonMap{}

    for k, v := range in {
        switch value := v.(type) {
        case jsonMap:
            res[k] = removeFromObject(value)
        case jsonMapList:
            list := []jsonMap{}
            for _, entry := range value {
                list = append(list, removeFromObject(entry))
            }
            res[k] = list
        case []interface{}:
            if len(value) == 1 {
                res[k] = value[0]
            } else {
                res[k] = value
            }
        default:
            res[k] = value
        }
    }

    return res
}

Question

How do I switch case to an object array, so that I can recursively resolve the objects within that array too?

  • 写回答

1条回答 默认 最新

  • dtjwov4984 2019-08-06 12:28
    关注

    You can use this function to remove the undesired arrays.

    func removearr(x interface{}) interface{} {
        switch val := x.(type) {
        case map[string]interface{}:
            for k, v := range val {
                val[k] = removearr(v)
            }
            return val
        case []interface{}:
            if len(val) == 1 {
                // remove array only if the value is not an object
                if _, ok := val[0].(map[string]interface{}); !ok {
                    return removearr(val[0])
                }
            }
    
            for i, v := range val {
                val[i] = removearr(v)
            }
            return val
        default:
            return x
        }
    }
    

    https://play.golang.com/p/mwo7Y2rJ_lc

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致