把json摊平成二维的map,kv

func json2KV(obj interface{}) map[string]interface{} {
	var data = make(map[string]interface{})
	rObj := reflect.ValueOf(obj)
	switch rObj.Kind() {
	case reflect.Map:
		iter := rObj.MapRange()
		for iter.Next() {
			for k, v := range json2KV(iter.Value().Interface()) {
				data[iter.Key().String()+"/"+k] = v
			}
		}
	case reflect.Slice, reflect.Array:
		for i := 0; i < rObj.Len(); i++ {
			for k, v := range json2KV(rObj.Index(i).Interface()) {
				data[fmt.Sprintf("[%d]/%s", i, k)] = v
			}
		}
	default:
		return map[string]interface{}{"": rObj.Interface()}
	}
	return data
}
posted @ 2020-08-15 18:03  白云辉  阅读(174)  评论(0编辑  收藏  举报