0

I want to turn

{
  "filename": "./readme.md",
  "line": 5,
  "rule": "MD009",
  "aliases": [
    "no-trailing-spaces"
  ],
  "description": "Trailing spaces"
}
{
  "filename": "./readme.md",
  "line": 6,
  "rule": "MD009",
  "aliases": [
    "no-trailing-spaces"
  ],
  "description": "Trailing spaces"
}

into

{"filename": "./readme.md","line": 5,"rule": "MD009","aliases": ["no-trailing-spaces"],"description":"Trailing spaces"}
{"filename": "./readme.md","line": 6,"rule": "MD009","aliases": ["no-trailing-spaces"],"description":"Trailing spaces"}

Basically each { } is on its own line

Is there a command that could do this? (I can't use tr)

My current solution is messy (Frankensteined together):

cat in.file | sed ':a;N;$!ba;s/\n//g' | sed -e $'s/}{/}\\\n{/g' > out.file
Ross M
  • 19
  • 6

1 Answers1

4

As always when it comes to working with JSON in scripts and from the command line, jq to the rescue:

$ jq -c . input.json
{"filename":"./readme.md","line":5,"rule":"MD009","aliases":["no-trailing-spaces"],"description":"Trailing spaces"}
{"filename":"./readme.md","line":6,"rule":"MD009","aliases":["no-trailing-spaces"],"description":"Trailing spaces"}
Shawn
  • 47,241
  • 3
  • 26
  • 60
  • Though relying on one json object per line seems pretty fragile and makes me suspect you're using the wrong tools for whatever you're doing, and/or XY problem territory. – Shawn May 28 '20 at 00:35
  • Yes I am trying to combine a linter's output with a jenkins plugin that needs a specfic type JSON format, the only other way would be to create a custom JSON parser but formatting the linter output seemed easier – Ross M May 28 '20 at 00:38
  • 1
    Actually, a single JSON object can reliably be reduced to a single line. Unquoted whitespace is irrelevant, and a newline cannot appear in a valid JSON string value. – chepner May 28 '20 at 00:40