golang golang嵌套地图相等

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang golang嵌套地图相等相关的知识,希望对你有一定的参考价值。

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
		}
	}
}

golang golang解析嵌套的地图

package main

import (
	"fmt"
)

func main() {
	m1 := map[string]interface{}{
		"a": 1,
		"b": 2,
		"c": map[string]interface{}{
			"d": 3,
			"e": 4,	
		},
		"f": 5,
	}
	
	m2 := make(map[string]interface{})
	for k, v := range m1 {
		if mm, ok := v.(map[string]interface{}); ok {
			for kx, vx := range mm {
				m2[k+"."+kx] = vx
			}
		} else {
			m2[k] = v
		}
	}
	for k, v := range m2 {
		fmt.Println(k, v)
	}
	fmt.Println("Hello, playground")
}

以上是关于golang golang嵌套地图相等的主要内容,如果未能解决你的问题,请参考以下文章

golang golang解析嵌套的地图

Golang 中的嵌套地图

golang golang map相等

golang golang地图列表

golang golang在嵌套映射中查找值

golang中判断两个slice是否相等