14

Having a list of strings (one per line) like

str1
str2
...

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

1 Answer 1

22

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.