Split a text file into a JSON array


To split a text file into a JSON array, with one element per line:

cat lines.txt | jq --raw-input --slurp 'split("\n")'

To ignore all blank lines, so the array has no empty strings:

cat lines.txt | jq --raw-input --slurp 'split("\n") | map(select(. != ""))'

You can use any delimiter. For example, Unix fortunes, which are delimited by a line with just “%”:

cat /usr/share/games/fortunes/computers | jq --raw-input --slurp 'split("\n%\n") | map(select(. != ""))'

To trim whitespace, add a gsub before the select:

cat lines.txt | jq --raw-input --slurp 'split("\n") | map(gsub("^ +| +$";""))'

To trim whitespace AND skip blank lines

cat lines.txt | jq --raw-input --slurp 'split("\n") | map(gsub("^ +| +$";"") | select(. != ""))'

Tags:  json

Share: