Selecting an element based on a search of a subelement array returns the element once for each matching item in the array

852 views Asked by At

Given the json

{ "games": [
{
    "id":1,
    "files": [ "foo.mp4" ]
},
{
    "id":2,
    "files": [ "foo.ogv",  "bar.ogv" ]
},
{
    "id":3,
    "files": [ "bar.ogv" ]
}
]}

and the command jq -r '.games[] | select(.files[] | contains("ogv"))' foo.json, json outputs an element once for every time it matches ogv in the subelement array. How do I get jq to output each matching element only once?

2

There are 2 answers

2
peak On BEST ANSWER

Using any would be more efficient than relying on unique. E.g.

jq -r '.games[] | select(any(.files[]; test("ogv")))'
0
SGDave On
jq -r '[.games[] | select(.files[] | contains("ogv"))] | unique | .[]' foo.json

or, since what I really want is just the id,

jq -r '[.games[] | select(.files[] | contains("ogv")) | .id] | unique | .[]' foo.json