1

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

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.