jq find value in object where key matches a regex

Viewed 50

In the JSON below, I need to find the value of the id key of every object where the value of state starts with "failed-"

[
  {
    "id": "RA_kwDOGETrS84EmTf2",
    "state": "uploaded"
  },
  {
    "id": "RA_kwDOGETrS84EmTf6",
    "state": "failed-4325423"
  },
  {
    "id": "RA_kwDOGETrS84EmTf7",
    "state": "uploaded"
  }
]

I got as far as extracting just the matching values of state:

.[] | .state | select(startswith("failed-"))

How do I find the corresponding values of id ?

2 Answers
.[] | select(.state | startswith("failed-")).id

Will output:

"RA_kwDOGETrS84EmTf6"

Trick is to pass state in the select() to startswith(), and then get .id of the result


Demo

.[] | select(.state | test("^failed")).id

is another way

Related