bashjq

converting lines to json in bash


I would like to convert a list into JSON array. I'm looking at jq for this but the examples are mostly about parsing JSON (not creating it). It would be nice to know proper escaping will occur. My list is single line elements so the new line will probably be the best delimiter.


Solution

  • I was also trying to convert a bunch of lines into a JSON array, and was at a standstill until I realized that -s was the only way I could handle more than one line at a time in the jq expression, even if that meant I'd have to parse the newlines manually.

    jq -R -s -c 'split("\n")' < just_lines.txt
    

    Easy peasy.

    Edit: I'm on jq ≥ 1.4, which is apparently when the split built-in was introduced.