Merging and Grouping Nested JSON based on a field in Go

Vaishnavi Abirami
1 min readJun 13, 2021

This blog is all about how do we merge and group nested JSON based on a common field for two different JSON in Go.

Following is the code snippet which is used to merge two JSON arrays and group the JSON arrays based on a common field. This snippet is totally type safe and doesn't cast any nested objects while processing them. In General type casting leads to panic error and we should always prefer using Structs for any data processing instead of Maps.

Let's look at line numbers 66–89 where we have a device Array and also the line numbers 99–118 where we have an app Array. Our Problem Statement here is to merge these two JSON Array into one based on the common field "appId".

The function ProcessData() does this merging and returns the JSON in the line numbers 139–167.

Once we get this Merged Data, we will then group the merge data based on the field "accountId" which is done by generateCombinedMap method. This groups the data which we got from ProcessData function in the field named "Items" under the corresponding accountId as "key". (the output of generateCombinedMap function is between line numbers 194–211).

--

--