Printing with jq multiple values in CSV or TSV formats

curl -s 'https://api.github.com/orgs/github/repos' | jq -r '.[] | [.id, .name, .stargazers_count] | @csv'

October 13, 2023bashoneliners

Explanation

The curl calls a GitHub API endpoint to get repository infos of the github organization in JSON format. The -s (or --silent) flag makes curl silent, suppressing messages about progress or errors.

The JSON content we want to filter using the subsequent jq looks something like this (showing here just the fields relevant for the example, but there are many many more):

[
  {
    "id": 3222,
    "name": "media",
    "stargazers_count": 293
  },
  {
    "id": 15929,
    "name": "albino",
    "stargazers_count": 222
  },
  {
    "id": 15930,
    "name": "hubahuba",
    "stargazers_count": 47
  },
  ...
]

The jq command filters and transforms the JSON content:

  • .[] for each object in the JSON array input, ...
  • [.id, .name, .stargazers_count] create a JSON array from the object's fields ...
  • @cvs convert a JSON array to a single string of comma separated values.

The -r (or --raw-output) flag makes jq print the output as raw values, which makes string values printed without enclosing double-quotes.

The output when using @csv:

3222,"media",293
15929,"albino",222
15930,"hubahuba",47
15931,"jquery-hotkeys",95
15932,"jquery-relatize_date",112

The output when using @tsv:

3222    media   293
15929   albino  222
15930   hubahuba        47
15931   jquery-hotkeys  95
15932   jquery-relatize_date    112