I struggled to find out a way to merge JSON arrays, so to save you time, I will show you an example here.
jq
I’m sure there are several ways to accomplish it with programming languages, I will use jq. Just run brew install jq
in your terminal if you use Mac.
Sample Data
fruits1.json
{
"data":[
{"name":"banana"},
{"name":"strawberry"},
{"name":"orange"}
]
}
fruits2.json
{
"data":[
{"name":"cherry"},
{"name":"blueberry"},
{"name":"apple"}
]
}
Merging
Execute the following jq command to merge the 2 arrays in 2 different JSON data.
jq -s '{ data: map(.data[]) }' fruits1.json fruits2.json
Here is the result.
{
"data": [
{
"name": "banana"
},
{
"name": "strawberry"
},
{
"name": "orange"
},
{
"name": "cherry"
},
{
"name": "blueberry"
},
{
"name": "apple"
}
]
}
If you just want a compact version of the same JSON data.
jq -sc '{ data: map(.data[]) }' fruits1.json fruits2.json
Here is the result.
{"data":[{"name":"banana"},{"name":"strawberry"},{"name":"orange"},{"name":"cherry"},{"name":"blueberry"},{"name":"apple"}]}
Though I don’t like jq, I had to accomplish it in a bash script I was working on. I could not contain my joy when I got it. 🙂