Can I transform a delimited string to a JSON array using jq?

184 views Asked by At

I'm writing a script that receives a delimited list of non-jSON data jq. My goal is to transform that list to a JSON array. The actual data is delimited with commas, but I could easily translate that to delimit by spaces or newlines, if that makes the problem easier.

I obviously can't pass this directly to jq since it's not JSON formatted data.

$ echo "A,B,C" | jq
jq: parse error: Invalid numeric literal at line 1, column 2

Does jq have a way to translate delimited non-JSON data into a JSON array?

Example

Input

ABC,123,XYZ,A"B,{1}

Output

["ABC", "123", "XYZ", "A\"B", "{1}"]

How can I achieve this using jq?

2

There are 2 answers

0
peak On BEST ANSWER

You could use the / operator, which splits the first string using the second as a separator, like so:

jq -cR './","' <<< 'ABC,123,XYZ,A"B,{1}'
["ABC","123","XYZ","A\"B","{1}"]

Or equivalently, using the split function:

jq -cR 'split(",")' <<< 'ABC,123,XYZ,A"B,{1}'

If you want to use a regex to help with the splitting, consider this example that trims spaces around the commas:

jq -cR '[splits(" *, *")]' <<< 'ABC, 123, XYZ, A"B, {1}'
1
sudocracy On

If you change the delimiter to a newline, you can use the -s option so that jq reads the entire input as if it were a JSON array. Notice the following examples:

§ echo $'1\n2\n3' | jq -s
[
  1,
  2,
  3
]
§ echo $'1\n2\n3' | jq -s 'length'
3