Skip to content

Instantly share code, notes, and snippets.

@aljorhythm
Created June 30, 2021 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aljorhythm/6b07213ba3b408c7dfcb44bbf261a93a to your computer and use it in GitHub Desktop.
Save aljorhythm/6b07213ba3b408c7dfcb44bbf261a93a to your computer and use it in GitHub Desktop.
golang merge json raw messages / maps
package merge
// quick and dirty merge of two json raw messages
// does not merge two json arrays
// MergeJson merges two json raw messages. If key
// exists in both maps, value from first argument will take precendence.
func MergeJson(json1 *json.RawMessage, json2 *json.RawMessage) (*json.RawMessage, error) {
map1 := map[string]interface{}{}
map2 := map[string]interface{}{}
err := json.Unmarshal(*json1, &map1)
if err != nil {
return nil, err
}
err = json.Unmarshal(*json2, &map2)
if err != nil {
return nil, err
}
mergedMap, err := MergeStringMaps(map1, map2)
if err != nil {
return nil, err
}
raw, err := json.Marshal(mergedMap)
message := json.RawMessage(raw)
return &message, err
}
// MergeStringMaps merges string maps. If key
// exists in both maps, value from first argument will take precendence.
func MergeStringMaps(map1 map[string]interface{}, map2 map[string]interface{}) (map[string]interface{}, error) {
mergedMap := map[string]interface{}{}
for k, v := range map2 {
mergedMap[k] = v
}
for k, v := range map1 {
mergedMap[k] = v
}
return mergedMap, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment