Skip to main content

Handling null (empty array) while converting json to csv with jq? [Resolved]

When trying to convert json to csv, I get an error about null with the following jq query:

printf "[]" | jq -r '(map(keys) | add | unique) as $cols | map(. as $row | $cols | map($row[.])) as $rows | $cols, $rows[] | @csv'

It gives the following error,

jq: error (at :0): Cannot iterate over null (null)

but works fine if the json array is non-empty and has an object in it:

$ printf '[{"a":1}]' | jq -r '(map(keys) | add | unique) as $cols | map(. as $row | $cols | map($row[.])) as $rows | $cols, $rows[] | @csv'
"a"
1

The jq grammar looks great, but I am not familiar with it as I just started to use this tool.

Can someone please explain how to patch the query to output nothing when the array is empty? (first example).


Question Credit: tinlyx
Question Reference
Asked July 18, 2019
Tags: ubuntu, json
Posted Under: Unix Linux
35 views
1 Answers

Your Answer