[jq] Select objects whose field value starts with a given string
You can combine select and startswith to select objects whose field value starts with a given string.
Output matching objects in order
The example below selects objects whose name starts with T.
echo '[{"name": "Taro", "age": 25},{"name": "Satoshi", "age": 30},{"name": "Takashi", "age": 35}]' | jq '.[] | select(.name | startswith("T"))'
The command produces the following output.
{
"name": "Taro",
"age": 25
}
{
"name": "Takashi",
"age": 35
}
.[] iterates over the elements of the array, and select keeps only the elements that match the condition. The output consists of two separate JSON objects, emitted one after the other.
Return the results as a single JSON array
To pass the results as an array to a later step, you can wrap the entire filter in [...].
echo '[{"name": "Taro", "age": 25},{"name": "Satoshi", "age": 30},{"name": "Takashi", "age": 35}]' | jq '[.[] | select(.name | startswith("T"))]'
The command produces the following output.
[
{
"name": "Taro",
"age": 25
},
{
"name": "Takashi",
"age": 35
}
]
If no objects match, the filter returns [].
When the target field is missing or null
If name is missing, .name evaluates to null. startswith requires a string, so a missing field or a null value causes an error.
echo '[{"age": 30}]' | jq '.[] | select(.name | startswith("T"))'
echo '[{"name": null, "age": 30}]' | jq '.[] | select(.name | startswith("T"))'
Both commands produce the following error.
jq: error (at <stdin>:1): startswith() requires string inputs
For a way to check whether the value is a string before processing it, see Avoiding the startswith() requires string inputs error (in Japanese).
jq