[{
"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])
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: .}
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
}
$
$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With