Finding all elements in a JSON dictionary which are not part of another dictionary with jq

Advertisements

I have to JSON files.

a.json:

[ 
  { key1: "foo", key2: "bar"},
  { key1: "foo", key2: "baz"},
  { key1: "bla", key2: "blubb"},
]

b.json:

[ 
  { key1: "foo", key2: "bar"},
  { key1: "foo", key2: "oof"},
  { key1: "bla", key2: "bla"},
]

My desired result is an array containing all the entrise of the first dictionary which are not part of the second one (equivalent to what the DISTINCT operator would do in SQL). So the expected output would be:

[ 
  { key1: "foo", key2: "baz"},
  { key1: "bla", key2: "blubb"},
]

How can I achieve this using jq?

>Solution :

Can’t find a valid duplicate, so posting this as an answer.


If you use -s (slurp), you can use object1 - object2 to get the difference between them:

jq -s  '.[0] - .[1]' a b

Will output:

[
  {
    "key1": "foo",
    "key2": "baz"
  },
  {
    "key1": "bla",
    "key2": "blubb"
  }
]

Leave a ReplyCancel reply