Home > Enterprise >  jq find value in object where key matches a regex
jq find value in object where key matches a regex

Time:09-09

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 ?

CodePudding user response:

.[] | 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

  • Related