Recursively merge JSON structures

7,806 views
Skip to first unread message

Peter Bourgon

unread,
Feb 24, 2013, 5:11:55 AM2/24/13
to golang-nuts
(Maybe this has been done before. I wasn't able to find anything.)

I want to recursively merge JSON maps. That is, given

{"foo": {"bar": 1}}
{"foo": {"baz": 2}}

I want

{"foo": {"bar": 1, "baz": 2}}

And so on, recursively. After a bit of thought, I landed at
http://github.com/peterbourgon/mergemap —but maybe there is a
better/smarter/stdlib way of doing this. Just thought I'd throw it
against the mailing list and see what happened.

Cheers,
Peter.

Andrew Jackman

unread,
Jun 8, 2016, 12:59:37 AM6/8/16
to golang-nuts, pe...@bourgon.org
According to the mergo documentation (https://github.com/imdario/mergo), "...they [structs inside maps] are not addressable using Go reflection." I take this to mean structs that are map elements. I think this means that the only way to successfully deeply merge complex data that includes maps is to use something like mergemap. Please let me know if you find differently, however.

Matt Harden

unread,
Jun 8, 2016, 7:14:20 PM6/8/16
to Andrew Jackman, golang-nuts, pe...@bourgon.org
Nothing inside a map is addressable; neither keys nor elements. If you store a pointer in a map then the object pointed to is addressable but the pointer itself is not (you can't get a pointer to the pointer, or change the pointer in place). This is different from arrays and slices where elements are addressable.

The builtin map type in Go does not support fast merging; you have to insert the elements from one map into the other one by one.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

roger peppe

unread,
Jun 9, 2016, 4:32:16 AM6/9/16
to Peter Bourgon, golang-nuts
A slower but more complete version might be this,
which will merge any JSON-marshalable values.

https://play.golang.org/p/8jlJUbEJKf

If you know that the values have already been unmarshaled
into interface{} and you don't mind the merge being
destructive, you could omit the outer merge wrapper.
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
Reply all
Reply to author
Forward
0 new messages