JQ – Handling Null (Empty Array) While Converting JSON to CSV with JQ

csvjqjsonUbuntu

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 <stdin>: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).

Best Answer

You can use a Error Suppression / Optional Operator: ? block to counter against an empty array invocation and return without throwing any errors to the console as

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

where .? can also be written explicitly using a try catch block as try .? and have rest of the filter following it. The part of the filter after the optional operator is skipped if the expression fails.

Related Question