Use jq to filter objects list with regex
My use case is filtering an array of objects that have an attribute that matches a particular regex and extract another attribute from that object.
Here is my dataset:
[
{name: 'Chris', id: 'aabbcc'},
{name: 'Ryan', id: 'ddeeff'},
{name: 'Ifu', id: 'aaddgg'}
]
First get each element of an array.
> data | jq '.[]'
{name: 'Chris', id: 'aabbcc'}
{name: 'Ryan', id: 'ddeeff'}
{name: 'Ifu', id: 'aaddgg'}
Pipe the elements to select
and pass an expression that will evaluate to truthy for each object.
> data | jq '.[] | select(true) | select(.name)'
{name: 'Chris', id: 'aabbcc'}
{name: 'Ryan', id: 'ddeeff'}
{name: 'Ifu', id: 'aaddgg'}
Then use the test
function to compare an attribute to a regex.
> data | jq '.[] | select(.id|test("a."))'
{name: 'Chris', id: 'aabbcc'}
{name: 'Ifu', id: 'aaddgg'}
Extract the name attribute for a more concise list.
> data | jq '.[] | select(.id|test("a.")) | .name'
Chris
Ifu
Read more about jq.
Tweet