8

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."}
]
1
  • 4
    How about just jq --slurp < my_file Commented Mar 11, 2020 at 14:10

3 Answers 3

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

...or, as suggested by @borrible:

jq --slurp . <in.jsonl >out.json
Sign up to request clarification or add additional context in comments.

Comments

4

For the task at hand, using jq's "slurp" option or [inputs] entails a potentially huge waste of resources.

A trivial but efficient solution can be implemented in awk as follows:

awk 'BEGIN {print "[";} NF==0{next;} n=="" {print;n++;next;} {print ","; print;} END {print "]"}'

An equivalent efficient solution in jq is possible using foreach and inputs, and is left as an exercise.

1 Comment

Note that sed golfs way better here! :-) stackoverflow.com/a/79650764/895245
0

Alternatively with sed:

echo [; sed '$!s/$/,/' input.jsonl; echo ]

or from stdin:

cat input.jsonl | ( echo [; sed '$!s/$/,/'; echo ] )

Here the $! in sed operates on all line except the last one: sed line range, all but the last line

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.