GolangNote

Golang笔记

Golang Json/map 合并/update

Permalink

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

Go: map 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 值覆盖,上面代码输出:

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

参考 https://github.com/peterbourgon/mergemap

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

Related articles

Golang 生成防识别的图片验证码

验证码 captcha 是对抗密码强力破解、垃圾信息的有效方式,一般用于用户注册、登录,当检测到频繁发帖时也会启用验证码。下面介绍用golang 生成防机器识别的图片验证码。...

Golang phantomjs 动态代理实现

phantomjs 是个很优秀的软件,虽然现在被chrome headless 抢了风头,但在某些特定场合,使用phantomjs 还是很方便,这里是介绍使用Go 实现动态代理。...

Write a Comment to "Golang Json/map 合并/update"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.17.1 Processed in 0ms