Home > Enterprise >  Select elements from json array based on 2 criteria
Select elements from json array based on 2 criteria

Time:08-04

I am fetching the list of issue comments on a specific PR with the following curl command

curl -sH "Accept: application/vnd.github json" -H "Authorization: token XXXXXXXXXX" https://api.github.com/repos/org/repo/issues/12/comments

The response format is according to the documentation as follows:

[
  {
    "id": 1,
    "node_id": "MDEyOklzc3VlQ29tbWVudDE=",
    "url": "https://api.github.com/repos/octocat/Hello-World/issues/comments/1",
    "html_url": "https://github.com/octocat/Hello-World/issues/1347#issuecomment-1",
    "body": "Me too",
    "user": {
      "login": "octocat",
      "id": 1,
      "node_id": "MDQ6VXNlcjE=",
      "avatar_url": "https://github.com/images/error/octocat_happy.gif",
      "gravatar_id": "",
      "url": "https://api.github.com/users/octocat",
      "html_url": "https://github.com/octocat",
      "followers_url": "https://api.github.com/users/octocat/followers",
      "following_url": "https://api.github.com/users/octocat/following{/other_user}",
      "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
      "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
      "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
      "organizations_url": "https://api.github.com/users/octocat/orgs",
      "repos_url": "https://api.github.com/users/octocat/repos",
      "events_url": "https://api.github.com/users/octocat/events{/privacy}",
      "received_events_url": "https://api.github.com/users/octocat/received_events",
      "type": "User",
      "site_admin": false
    },
    "created_at": "2011-04-14T16:00:49Z",
    "updated_at": "2011-04-14T16:00:49Z",
    "issue_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347",
    "author_association": "COLLABORATOR"
  }
]

I know that I can get the last comment's author's username by piping the output to jq '.[-1].user.login'

How can I get from ALL the comments matching user.login=foobar the most recent one?

CodePudding user response:

select is the function that filters by criteria.

Use with map to retain the array structure

jq 'map(select(.user.login == "foobar"))'

Or iterate and get just the matching items

jq '.[] | select(.user.login == "foobar")'
  • Related