Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting lines to json in bash

Tags:

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.

like image 468
jcalfee314 Avatar asked Oct 09 '14 20:10

jcalfee314


People also ask

What is jq command in bash?

jq command is used not only for reading JSON data but also to display data by removing the particular key. The following command will print all key values of Students. json file by excluding batch key. map and del function are used in jq command to do the task.

Can jq create JSON?

jq is an amazing little command line utility for working with JSON data. We've written before about how you can use jq to parse JSON on the command line, but in this post I want to talk about using jq to create JSON data from scratch or make changes to existing data.

How JSON array looks like?

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.


1 Answers

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 
  • -R to read raw input
  • -s to read all input as a single string
  • -c to not pretty print the output

Easy peasy.

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

like image 115
chbrown Avatar answered Oct 05 '22 12:10

chbrown