Combining arrays from a stream of objects

Viewed 40

I'm struggling to work with this a little more complex json structure:

{
  "name": "item1",
  "path":
    {"mapping":
      [
        {"position": {"node_id": "1"}, "rank": "1"},
        {"position": {"node_id": "2"}, "rank": "2"},
        {"position": {"node_id": "3"}, "rank": "3"},
        {"position": {"node_id": "6"}, "rank": "4"}
      ]
    }
}

{
  "name": "item2",
  "path":
    {"mapping":
      [
        {"position": {"node_id": "1"}, "rank": "1"},
        {"position": {"node_id": "5"}, "rank": "2"},
        {"position": {"node_id": "3"}, "rank": "3"},
        {"position": {"node_id": "4"}, "rank": "4"}
      ]
    }
}

All I want are the unique "node_ID" entries overall, I don't care to which object they belong. With [.path.mapping[].position.node_id] I get an array per object, and I can't find any example on how to combine those to use unique on them.

Desired output is:

1
2
3
4
5
6

What is the best way to achieve this?

1 Answers

With -n/--null-input option you can get inputs by the keyword inputs and construct a single array out of values in them. E.g.:

$ jq -nr '[inputs.path.mapping[].position.node_id] | unique[]' file
1
2
3
4
5
6
Related