Skip to content

Instantly share code, notes, and snippets.

@qzaidi
Last active August 19, 2022 07:23
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 qzaidi/ad2c66433c2b9a0b0a1c949098ade589 to your computer and use it in GitHub Desktop.
Save qzaidi/ad2c66433c2b9a0b0a1c949098ade589 to your computer and use it in GitHub Desktop.
jq cheat sheet

Convert json to csv

cat json | jq -r '(.[0] | keys_unsorted) as $keys | $keys, map([.[ $keys[] ]])[] | @csv'

Alternative method, handles nested objects

Create a file named filter.jq

def tocsv:
    (map(keys)
        |add
        |unique
        |sort
    ) as $cols
    |map(. as $row
        |$cols
        |map($row[.]|tostring)
    ) as $rows
    |$cols,$rows[]
    | @csv;

tocsv

Run as jq -r -f

For example, for multiple files in a directory, to convert and generate a single csv

for i in `ls *json | sort -n`; do echo $i >> data.csv; jq .data $i | jq -r -f filter.jq >> data.csv; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment