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 TSV (tab delimited) format. Below are examples of how to convert JSON to TSV with jq.

Converting JSON to TSV

In order to convert JSON to TSV 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 tab delimited format using the @tsv syntax.

jq -r '.myarray | @tsv'

Here is a complete example with a sample JSON input:

echo '{"key1":"val1", "myarray":["abc", "def", "ghi"]}' | jq -r '.myarray | @tsv'
abc	def	ghi

If you would like to create a TSV from fields that are not in an array, then you can create the array with jq. The following example will create a TSV from the key1 field and the first element in myarray:

echo '{"key1":"val1", "myarray":["abc", "def", "ghi"]}' | jq -r '[.key1, .myarray[0]] | @tsv'
val1	abc

Enclosing Fields in Quotes

By default each tab delimited record will be enclosed in quotes. The -r option used in the examples above will remove the outer quotes from the output.

Leave a Reply

Convert JSON to TSV with jq