skip to Main Content

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


  1. 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}'
    
    Login or Signup to reply.
  2. 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 $'1n2n3' | jq -s
    [
      1,
      2,
      3
    ]
    
    § echo $'1n2n3' | jq -s 'length'
    3
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search