Home
| Colors: |
March 2026

Filter the First N Number of Items from a JSON Array with jq

Use jq's [start:finish] to filter JSON to remove all but the first N number of items from a JSON array. For example:

For example:

echo '{ "items": ["a", "b", "c", "d"] }' \
| jq '.items = .items[0:2]'
Output:
{
  "items": [
    "a",
    "b"
  ]
}

More Range

The start and finish values are indexes. They can pull other ranges of the array beyond starting with the first item. For example:

echo '{ "items": ["a", "b", "c", "d"] }' \
| jq '.items = .items[1:3]'
Output:
{
  "items": [
    "b",
    "c"
  ]
}

The key being that the overall structure of the JSON remains the same.

jq continues to impress.

-a

end of line

References

jq

the lightweight and flexible command-line JSON processor.