79183228

Date: 2024-11-13 02:33:57
Score: 0.5
Natty:
Report link

Here's an extension of Abdul's answer that also adds a line of dashed separators to help guide the eye for column widths. It was much more complicated to write than I expected, but that's why it was fun (? 🥴).

Saved into table.jq:

# Convert a list of similar objects into a table of values
# Modified from: https://stackoverflow.com/a/77054233/2613780
# Example usage:
#   jq --raw-output --from-file table.jq <<< '[ {"a": "able"}, {"b": "bacon"}, {"c": "cradle"} ]' | column -ts $'\t'

# Convert all values to strings
map( map_values(tostring) )
# Get column headings
| ( map(keys) | add | unique ) as $column_titles
# Create an object from column_titles where all values are set to null
| ( reduce $column_titles[] as $title ({}; . + {$title: null}) ) as $null_object
# Add all "columns" to all objects (the order is important, we want any actual values to override nulls)
| map($null_object + .)
# Create column separators
| (
  # Add an object with the column headings as values
  . + [reduce $column_titles[] as $column ({}; . + {$column: $column})]
  # Sort all object keys alphabetically
  | map(to_entries | sort_by(.key) | from_entries)
  # Create a row of dashes matched to max column widths
  | ( map(map(length)) | transpose | map(max * "-") )
) as $seps
# Convert all values to table rows
| map(. as $row | $column_titles | map($row[.])) as $rows
# Output table
| $column_titles, $seps, $rows[]
| @tsv

Also here in this GitHub Gust.

This is too long for a "one-liner" now but I enjoyed working on it. It's probably a little inefficient (I just love using variables) so I'd love to hear some feedback - it seems like it works roughly on O(n) time as far as I can tell!

Adding | column -ts $'\t' to the end of every usage is annoying enough that I've made a whole script just to use it called json-list-to-table you can also find in the Gist above.

Tested with a few "interesting" cases:

  1. The example above:

    jq --raw-output --from-file table.jq <<< '[ {"a": "able"}, {"b": "bacon"}, {"c": "cradle"} ]' | column -ts $'\t'
    
  2. Using the reqres.in test API:

    curl https://reqres.in/api/users?per_page=12 | jq '.data' | jq --raw-output --from-file table.jq | column -ts $'\t'
    
  3. A bunch of image layers from the DockerHub API:

    curl --location --silent --show-error "https://registry.hub.docker.com/v2/namespaces/library/repositories/python/tags" | jq '[.results[].images[]]' | jq --raw-output --from-file table.jq | column -ts $'\t'
    
Reasons:
  • Blacklisted phrase (1): stackoverflow
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (0.5):
Posted by: Fragment