Ask Your Question
0

How can I filter an array of objects using a condition using jq?

asked 2023-07-18 00:23:50 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-18 00:38:02 +0000

lalupa gravatar image

To filter an array of objects using a condition using jq, you can use the select() function. The select() function takes a boolean expression that evaluates to true or false for each element in the array. Elements for which the expression evaluates to true are included in the output, while elements for which the expression evaluates to false are excluded.

Here's an example of an array of objects:

[
  {
    "name": "Alice",
    "age": 25
  },
  {
    "name": "Bob",
    "age": 30
  },
  {
    "name": "Charlie",
    "age": 35
  }
]

To filter this array to include only objects where the age property is greater than 30, you can use the following command:

jq '.[] | select(.age > 30)'

This will output the following:

{
  "name": "Charlie",
  "age": 35
}

The . in .[] is a shorthand for [], which tells jq to process each element in the input array. The select(.age > 30) expression selects only the elements where the age property is greater than 30.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-18 00:23:50 +0000

Seen: 14 times

Last updated: Jul 18 '23