2

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.

Thor
  • 45,082
  • 11
  • 119
  • 130
Bas Harenslak
  • 2,591
  • 14
  • 14

2 Answers2

2

Short and simple:

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

Fancy but fast:

label $top | .[] | if .id == 1 then break $top else . end
peak
  • 105,803
  • 17
  • 152
  • 177
  • If you want to include the seeked object, just increment index: `.[0: map(.id) | index(1)+1]` – poka Oct 02 '20 at 21:38
0

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!

Bas Harenslak
  • 2,591
  • 14
  • 14