jq: How to Merge JSON Files

Updated

Learn how to merge two or more JSON files with jq

jq: How to Merge JSON Files

Before we start, make sure you have jq installed on your computer. On a Mac, you can install it with Homebrew:

brew install jq

First, open your terminal and navigate to the folder with your JSON files. To merge two objects, run:

jq -s 'add' file1.json file2.json > merged.json

The -s flag slurps both files into one array, and add merges them from left to right, so the later file wins when a key appears in both. Just be careful: this is a shallow merge. A nested object in the second file replaces the whole object from the first one.

For a deep merge that keeps the nested keys, use the * operator inside reduce:

jq -s 'reduce .[] as $item ({}; . * $item)' file1.json file2.json > merged.json

You can pass as many files as you like, or a wildcard like *.json. Open merged.json to make sure every setting is there.

If both files hold arrays of objects that share an id, you can join them: jq -s 'add | group_by(.id) | map(add)' file1.json file2.json.