https://github.com/zapling/mergemap
Go library to recursively merge JSON maps
https://github.com/zapling/mergemap
Last synced: 8 days ago
JSON representation
Go library to recursively merge JSON maps
- Host: GitHub
- URL: https://github.com/zapling/mergemap
- Owner: zapling
- License: bsd-2-clause
- Fork: true (peterbourgon/mergemap)
- Created: 2022-02-16T14:34:41.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2022-02-18T07:35:16.000Z (almost 4 years ago)
- Last Synced: 2025-10-10T06:49:16.052Z (4 months ago)
- Language: Go
- Homepage: https://pkg.go.dev/github.com/zapling/mergemap
- Size: 14.6 KB
- Stars: 1
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# mergemap
mergemap is a Go library to recursively merge JSON maps.
This is a fork of [peterbourgon/mergemap](github.com/peterbourgon/mergemap) which adds support for
different merge strategies.
## Behavior
mergemap performs a simple merge of the **src** map into the **dst** map. That
is, it takes the **src** value when there is a key conflict, this can be customised by configuring
another merge strategy.
When there is a conflicting key that represents a map in both src and dst, then mergemap recursively
descends into both maps, repeating the same logic. The max recursion depth is set by **mergemap.MaxDepth**.
## Usage
```go
var m1, m2 map[string]interface{}
json.Unmarshal(buf1, &m1)
json.Unmarshal(buf2, &m2)
merged := mergemap.Merge(m1, m2)
```
If you need more customised behavior you can use `MergeWithConfig`
```go
payload1 := `{"my-key": "first-value"}`
payload2 := `{"my-key": "second-value"}`
var m1, m2 map[string]interface{}
json.Unmarshal(payload1, &m1)
json.Unmarshal(payload2, &m2)
config := map[string]interface{}{
"my-key": mergemap.StrategyFirstValue,
}
merged := mergemap.MergeWithConfig(m1, m2, config)
fmt.Printf("%v", merged) // map[my-key:first-value]
```
There is a few merge strategies already configuerd, but you can easily add or remove ones by modifying the
`mergemap.DefaultMergeStrategies` map.
The currently supported strategies are:
- Last value (default)
- First value
- Minimum value
- Maximum value
See the test file for some pretty straightforward examples.