把两个map 合并,功能与 python 的 update 功能相同

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main

import (
	"encoding/json"
	"fmt"
	"reflect"
)

var jsonMergeDepth = 32

func main() {
	buf1 := []byte(`{"a":1,"b":2}`)
	buf2 := []byte(`{"c":3,"d":4,"a":"aaa"}`)

	var m1, m2 map[string]interface{}

	json.Unmarshal(buf1, &m1)
	json.Unmarshal(buf2, &m2)

	merged := JsonMerge(m1, m2)

	fmt.Println(merged)
}

func JsonMerge(dst, src map[string]interface{}) map[string]interface{} {
	return jsMerge(dst, src, 0)
}

func jsMerge(dst, src map[string]interface{}, depth int) map[string]interface{} {

	if depth > jsonMergeDepth {
		return dst
		// panic("too deep!")
	}

	for key, srcVal := range src {

		if dstVal, ok := dst[key]; ok {

			srcMap, srcMapOk := jsMapify(srcVal)
			dstMap, dstMapOk := jsMapify(dstVal)

			if srcMapOk && dstMapOk {
				srcVal = jsMerge(dstMap, srcMap, depth+1)
			}
		}

		dst[key] = srcVal
	}

	return dst
}

func jsMapify(i interface{}) (map[string]interface{}, bool) {

	value := reflect.ValueOf(i)

	if value.Kind() == reflect.Map {

		m := map[string]interface{}{}

		for _, k := range value.MapKeys() {
			m[k.String()] = value.MapIndex(k).Interface()
		}

		return m, true
	}

	return map[string]interface{}{}, false
}

注意

若有重复的key,会把原来key 值覆盖,上面代码输出:

1
map[a:aaa b:2 c:3 d:4]

本文网址: https://golangnote.com/topic/209.html 转摘请注明来源