Merging two JSON files

Having two large JSON files with one common element, how can you merge them? Editing by hand not so nice if the files contain hundreds of elements.

For example, you have a large JSON file of locations:

{
  "name": "Oulu",
  "lat": 65.013784817,
  "lon": 25.47209907
},

And then you also have a large JSON file of location codes for the commune:

{
  "name": "Oulu",
  "code": "564"
},

And you would like to merge these into a one JSON file and parse the commune code, name, and location data at one go.

You can do this with jq using the following command:

./jq-osx-amd64 --slurpfile file2 codes.json.txt '
  INDEX($file2[]; .name) as $dict
  | $dict[.name] as $x
  | if $x then . + $x else empty end
'  coords.json.txt > out.json

And as a result, you get your JSON element merged in one file:

{
  "name": "Oulu",
  "lat": 65.013784817,
  "lon": 25.47209907,
  "code": "564"
},

Much faster than copying and pasting or implementing your own JSON merger.