How do I find an attribute in a JSON file that contains any letter of the alphabet using jq?

479 Views Asked by At

I have a JSON document I am querying for some data. I need to loop through the IDs and find any IDs that contain a letter. Currently I have:

cat results.json | jq '.array|map(select( (.id|contains("a")) or (.id|contains("b")) ))' etc. etc.

How can I write a more efficient query/regex to do this in one contains() function e.g. something like:

cat results.json | jq '.array|map(select( (.id|contains("a-z")) ))' etc. etc.

Thanks!

2

There are 2 best solutions below

1
On

To check whether a string contains a letter of the alphabet, you could use test("[A-Za-z]").

Consider also character classes, e.g.

test("\\p{Alpha}")
test("\\p{L}")

For safety, you’ll probably also want to select or check for strings, e.g. using the form:

select( .id | strings | test(...) )
0
On

Given this input:

[
  10,
  false,
  "foo",
  12,
  true,
  "bar",
  ":)",
  "99",
  "a99"
]

The following JQ filter:

map(select(strings|test("\\p{alpha}")))

will produce the following output:

[
  "foo",
  "bar",
  "a99"
]