Search code examples
jsonbashjqjsonlines

Convert sequence of JSON lines (JSONL) to JSON array


I have a file where each line is a JSON object. I'd like to convert the file to a JSON array.

The file looks something like this:

{"address":"[email protected]", "topic":"Some topic."}
{"address":"[email protected]", "topic":"Another topic."}
{"address":"[email protected]", "topic":"Yet another topic."}

I'm using bash and jq.

I tried

jq --slurp --raw-input 'split("\n")[:-1]' my_file

But that just treats each line as a string creating a JSON array of strings.

[
  "{\"address\":\"[email protected]\", \"topic\":\"Some topic.\"}",
  "{\"address\":\"[email protected]\", \"topic\":\"Another topic.\"}",
  "{\"address\":\"[email protected]\", \"topic\":\"Yet another topic.\"}"
]

I'd like to have:

[
  {"address":"[email protected]", "topic":"Some topic."},
  {"address":"[email protected]", "topic":"Another topic."},
  {"address":"[email protected]", "topic":"Yet another topic."}
]

Solution

  • jq -n '[inputs]' <in.jsonl >out.json
    

    ...or, as suggested by @borrible:

    jq --slurp . <in.jsonl >out.json