Remove mismatch and add missing json jq

It is quite simple once you figure out how to find the difference among two list items and add/unique them. One way would be to

jq --slurpfile s 2.json -f script.jq 1.json

Where my script contents are

#!/usr/bin/env jq -f

# backup list_1, list_2 from 1.json
.list_1 as $l1  |
.list_2 as $l2  |
# Perform the operation of removing file1 keys not present in 2.json
# for both list_1 and list_2
( ( $l1 - ( $l1 - $s[].list_1 ) ) +  $s[].list_1 | unique ) as $f1 |
( ( $l2 - ( $l2 - $s[].list_2 ) ) +  $s[].list_2 | unique ) as $f2 |
# Update the original result 1.json with the modified content
.list_1 |= $f1 |
.list_2 |= $f2

or directly from the command line as

jq --slurpfile s 2.json '
  .list_1 as $l1  |
  .list_2 as $l2  |
  ( ( $l1 - ( $l1 - $s[].list_1 ) ) +  $s[].list_1 | unique ) as $f1 |
  ( ( $l2 - ( $l2 - $s[].list_2 ) ) +  $s[].list_2 | unique ) as $f2 |
  .list_1 |= $f1 |
  .list_2 |= $f2
' 1.json

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top