Skip to content

Instantly share code, notes, and snippets.

@orirawlings
Created August 2, 2022 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orirawlings/aa369fcb40332e78d1038c33557e1502 to your computer and use it in GitHub Desktop.
Save orirawlings/aa369fcb40332e78d1038c33557e1502 to your computer and use it in GitHub Desktop.
Convert arbitrary array of JSON objects into columnar CSV data where each column corresponds to a unique key path found in any of the objects.
#! /usr/local/bin/jq -r -f
#
# Convert arbitrary array of JSON objects into columnar CSV data where each
# column corresponds to a unique key path found in any of the objects.
#
# For example:
#
# $ echo '[ {"a": 1, "b":{"c":"d"}}, {"e": 42} ]' | csv-ify
# "a","b.c","e"
# 1,"d",
# ,,42
#
(
[ .[] | paths(scalars) ] | unique
) as $paths |
[
$paths[] | map(tostring) | join(".")
] as $headers |
(
$headers | @csv
),
(
.[] | [ getpath($paths[]) ] | @csv
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment