Bas Harenslak
Bas Harenslak

Reputation: 3084

Select elements before nth element with jq

I'm stuck on the following json with jq. The elements below are sorted descending by some timestamp (not included in the json). I need to select the ids before id X. E.g. select ids before id 1 should return 2, 3 and 5.

[
  {
    "id": 2,
    "somekey": "somevalue"
  },
  {
    "id": 3,
    "somekey": "somevalue"
  },
  {
    "id": 5,
    "somekey": "somevalue"
  },
  {
    "id": 1,
    "somekey": "somevalue"
  },
  {
    "id": 4,
    "somekey": "somevalue"
  }
]

Any idea how to do this in a one-liner with jq? Specifically the "select elements before" part.

Upvotes: 2

Views: 404

Answers (2)

peak
peak

Reputation: 116919

Short and simple:

.[0: map(.id) | index(1)]

Fancy but fast:

label $top | .[] | if .id == 1 then break $top else . end

Upvotes: 2

Bas Harenslak
Bas Harenslak

Reputation: 3084

I figured out this query:

[.[].id] | to_entries | .[0:map(select(.value==1))[].key][].value

If you know a less verbose way to achieve the same, let me know!

Upvotes: 0

Related Questions