Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform a list of strings to JSON array using jq

Having a list of strings (one per line) like

str1
str2
...

how do I convert these into the JSON list ["str1", "str2", ...]?

like image 806
Halle Knast Avatar asked Feb 06 '26 23:02

Halle Knast


1 Answers

Assuming that the input is given on stdin, the following command solves the problem:

jq -Rn '[inputs]'

The flag -R reads the input as "raw" (i.e. unquoted strings) and -n hands over stdin to inputs (slurping with -s doesn't work because when combined with -R, it reads the whole input a single string). Add -c to print the JSON on one line like in the question.

Any empty lines (like a trailing newline) may be skipped by adding a little filter:

jq -Rn '[inputs|select(length>0)]'

If the strings are separated by other characters like ,, the string may be split with

jq -R 'split(",")'

This could be used to split on \n as well for solving the above case, but my (unverified) assumption is that the above solution is more portable with systems using other line terminators.

like image 89
Halle Knast Avatar answered Feb 08 '26 14:02

Halle Knast