zhiruchen
7/14/2017 - 6:41 AM

golang nested map equal

golang nested map equal

func main() {
	//var data Data
	data := map[string]interface{}{
		"A": 1,
		"B": 2,
		"C": map[string]interface{}{
			"D": 3,
			"E": 4,
			"G": map[string]interface{}{
				"H": 123,
				"Q": 456,
			},
		},
		"F":    5,
		"DATE": "dd",
	}

	newMap1 := flattenMap(data)
	log.Printf("%v\n", newMap1)

	data2 := map[string]interface{}{
		"A": 1,
		"B": 2,
		"C": map[string]interface{}{
			"D": 3,
			"E": 4,
			"G": map[string]interface{}{
				"H": 123,
				"Q": 456,
			},
		},
		"F":    5,
		"DATE": "dd",
	}
	newMap2 := flattenMap(data2)
	log.Printf("%v\n", newMap2)

	log.Println(mapEqual(newMap1, newMap2))
}

func mapEqual(m1, m2 map[string]interface{}) bool {
	for k, v := range m1 {
		v1, ok := m2[k]
		if !ok {
			return false
		}
		if v1 != v {
			return false
		}
		////v2, ok1 := v.(int)
		////v3, ok2 := v1.(int)
		////if !ok1 || !ok2 || v2 != v3 {
		////	return false
		////}
		//switch v.(type) {
		//case int:
		//	v2, ok1 := v1.(int)
		//	if !ok1 {
		//		return false
		//	}
		//	v3 := v.(int)
		//	if v2 != v3 {
		//		return false
		//	}
		//
		//case time.Time:
		//
		//}
	}
	return true
}

func map2Json(m map[string]interface{}) (string, error) {
	b, err := json.Marshal(&m)
	return string(b), err
}

func flattenMap(m map[string]interface{}) map[string]interface{} {
	d := make(map[string]interface{})
	for k, v := range m {
		v1, ok := v.(map[string]interface{})
		if ok {
			flatMap(d, v1, k)
		} else {
			d[k] = v
		}
	}
	return d
}

func flatMap(d, m map[string]interface{}, oldKey string) {
	for k, v := range m {
		v1, ok := v.(map[string]interface{})
		if ok {
			flatMap(d, v1, oldKey+"."+k)
		} else {
			d[oldKey+"."+k] = v
		}
	}
}