Josemy
Josemy

Reputation: 838

How to append extra newline on each json with jq

I know that jq . makes the json pretty and indented, but I would like to add 2 extra newlines after each json. Meaning:

Input:

{"foo": "bar", "say":"what"}
{"foo2": "bar2", "say2":"what2"}

Wanted output:

{
  "foo": "bar", 
  "say":"what"
}


{
  "foo2": "bar2", 
  "say2":"what2"
}

Is that possible with jq somehow? I have tried cat file.json | sed G | jq . without success and actually I wanted to avoid some sed magic thinking that maybe jq could do all the work.

Upvotes: 2

Views: 2218

Answers (4)

glenn jackman
glenn jackman

Reputation: 246807

Using some unreadable perl to only print extra newlines between the closing brace and the opening brace

jq . file | perl -0777 -pe 's/^\}\n\{/}\n\n\n{/gm'

Upvotes: 0

0stone0
0stone0

Reputation: 43983

Don't think is capable of producing such an output in general.


  • We can use some magic to insert a newline on each line containing just an }.

    • sed 's/^\}/&\n\n/'
  • Since there will be a trailing newline, we'll use head -c -2 to remove the last lines.


Output:

{
  "foo": "bar",
  "say": "what"
}


{
  "foo2": "bar2",
  "say2": "what2"
}

Example on my local machine:

$ cat input.json
{"foo": "bar", "say":"what"}
{"foo2": "bar2", "say2":"what2"}
$
$
$ jq '.' input.json | sed 's/^\}/&\n\n/' | head -c -2
{
  "foo": "bar",
  "say": "what"
}


{
  "foo2": "bar2",
  "say2": "what2"
}
$

edit

  • Added ^ to the command to only match } on the start of the line.

    sed 's/\}/&\n\n/' --> sed 's/^\}/&\n\n/'

Upvotes: 2

Pierre François
Pierre François

Reputation: 6061

You can pipe the output of jq . to sed as follows:

jq . file.json | sed '/}/s//&\n\n/'

Upvotes: 1

peak
peak

Reputation: 116740

So long as none of the incoming JSON texts is a string, you could write:

jq -r '., "", ""' file.json

Upvotes: 2

Related Questions