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
Answers
You could use the
/
operator, which splits the first string using the second as a separator, like so:Or equivalently, using the
split
function:If you want to use a regex to help with the splitting, consider this example that trims spaces around the commas:
If you change the delimiter to a newline, you can use the
-s
option so thatjq
reads the entire input as if it were a JSON array. Notice the following examples: