Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter by Regex in JQ

[{
  "Address": "The Sq"
 },
 {
  "Address": "1 Bridge Rd"
}]

With the following JSON, how do I write a script using JQ to filter for a regex where i want the result to be only Address's with numbers as the first character. I build this JSON using

map({ Address: .[].payload.address })

how do i add to this to filter for the regex expression I want (which is \A[0-9])

like image 334
user49 Avatar asked Jun 15 '18 01:06

user49


2 Answers

If you tacked the following filter onto the one you already have, then you'd get the output shown below:

map(select(.Address | test("^[0-9]")))

Output:

[
  {
    "Address": "1 Bridge Rd"
  }
]

For robustness, you might like to consider adding ? after the test:

map(select(.Address | test("^[0-9]")?))

Or, you could combine the two calls to map in various ways. You might like to consider:

.[].payload.address | select(test("^[0-9]")?) | {Address: .}
like image 200
peak Avatar answered Oct 09 '22 03:10

peak


Though the accepted answer works, I find this more readable

$
$ echo '[{"Address": "The Sq", "n": 1}, {"Address": "1 Bridge Rd", "n": 2}]' | \
  jq '.[] | .Address | select(.|test("^[0-9]"))'

"1 Bridge Rd"
$
$ echo '[{"Address": "The Sq", "n": 1}, {"Address": "1 Bridge Rd", "n": 2}]' | \
  jq '.[] | select(.Address|test("^[0-9]"))'

{
  "Address": "1 Bridge Rd",
  "n": 2
}
$

If you want to do a little different filtering:

$ echo '[{"name": "john doe", "sex": "male", "age": 26, "occupation": "city planner", "cod": "asphyxiation"}, {"name": "jane doe", "sex": "male", "age": 24, "occupation": "beautician", "cod": "strangulation"}, {"name": "crispy lips", "sex": "male", "age": 38, "occupation": "convicted killer"} ]' > in.json
$ cat in.json | jq .
[
  {
    "name": "john doe",
    "sex": "male",
    "age": 26,
    "occupation": "city planner",
    "cod": "asphyxiation"
  },
  {
    "name": "jane doe",
    "sex": "male",
    "age": 24,
    "occupation": "beautician",
    "cod": "strangulation"
  },
  {
    "name": "crispy lips",
    "sex": "male",
    "age": 38,
    "occupation": "convicted killer"
  }
]
$

Then we can do basic regex-filter/transform like this:

$ cat in.json | jq '.[] | .name'
"john doe"
"jane doe"
"crispy lips"
$
$ cat in.json | jq '.[] | .name | select(.|test(".*doe"))'
"john doe"
"jane doe"
$
$ cat in.json | jq '.[] | select(.name|test(".*doe"))'
{
  "name": "john doe",
  "sex": "male",
  "age": 26,
  "occupation": "city planner",
  "cod": "asphyxiation"
}
{
  "name": "jane doe",
  "sex": "male",
  "age": 24,
  "occupation": "beautician",
  "cod": "strangulation"
}
$ 
$ cat in.json | jq '.[] | select(.name|test(".*doe")) | {n: .name, a: .age}'
{
  "n": "john doe",
  "a": 26
}
{
  "n": "jane doe",
  "a": 24
}
$ 
$ 
like image 27
Kashyap Avatar answered Oct 09 '22 03:10

Kashyap