Text file to json array with jq

Lets say we need convert a text file into json array a process it. More information about jq itself can be found in the manual. First of all let’s create a test file with the first four Greek alphabet letters:

$ cat > greek.txt <<END

Each line can be converted to the element of an array. Tool jq is invoked with options --raw-input/-R (each line of text is passed to the filter as a string) and --compact-output / -c (no pretty output, each object is on a single line):

$ jq -cR 'split("\n")' greek.txt

Array brackets can be removed:

$ jq -cR 'split("\n") | .[]' greek.txt

Now we may search in similar way like in tool grep. Lets print all lines, for example, with letter “e”:

$ jq -cR 'split("\n") | .[] | select(test(".*e"))' greek.txt
This entry was posted in workday. Bookmark the permalink.

Leave a Reply