jq
is a lightweight JSON command line processor that makes many JSON processing tasks very easy. A common task when working with JSON is to convert records into a CSV format. Below are examples of how to convert JSON to CSV with jq.
Converting JSON to CSV
In order to convert JSON to CSV with jq, the input data must be in a JSON array. If the array doesn’t already exist it can be built with jq.
This example will take all the items in myarray
and convert them into a comma delimited format using the @csv
syntax.
jq -r '.myarray | @csv'
Here is a complete example with a sample JSON input:
echo '{"key1":"val1", "myarray":["abc", "def", "ghi"]}' | jq -r '.myarray | @csv'
"abc","def","ghi"
If you would like to create a CSV from fields that are not in an array, then you can create the array with jq before converting to CSV. The following example will create a CSV from the key1
field and the first element in myarray
:
echo '{"key1":"val1", "myarray":["abc", "def", "ghi"]}' | jq -r '[.key1, .myarray[0]] | @csv'
"val1","abc"
Enclosing Fields in Quotes
By default each CSV record as well as all its fields will be enclosed in quotes. The -r
option used in the examples above will remove the outer quotes from the output.