h.b h.b - 3 months ago 9
JSON Question

Parsing JSON "Pretty" format to one liner

I run a command on one of my systems and it spits out JSON "pretty" format like so:

[
{
"server": "servename1",
"i.p": 127.0.0.1,
"domain": "generic",
"OS": "RHEL",
"Version": 7.0
},
{
"server": "servename2",
"i.p": 127.0.0.1,
"domain": "generic",
"OS": "RHEL",
"Version": 7.0
},
{
"server": "servename3",
"i.p": 127.0.0.1,
"domain": "generic",
"OS": "RHEL",
"Version": 7.0
}
]


I need to parse these paragraphs in one liners like so:

[{"server":"servename1","i.p":127.0.0.1,"domain":"generic","OS":"RHEL","Version":7.0},
{"server":"servename2","i.p":127.0.0.1,"domain":"generic","OS":"RHEL","Version":7.0},
{"server":"servename3","i.p":127.0.0.1,"domain":"generic","OS":"RHEL","Version":7.0},]


What is the easiest way to do this? I am tried using SED and JQ but couldn't get it.

Answer

If your input is always that regular:

$ awk '{ORS=(/},|\]/?RS:""); gsub(/[[:blank:]]+/,""); sub(/}$/,"},")}1' file
[{"server":"servename1","i.p":127.0.0.1,"domain":"generic","OS":"RHEL","Version":7.0},
{"server":"servename2","i.p":127.0.0.1,"domain":"generic","OS":"RHEL","Version":7.0},
{"server":"servename3","i.p":127.0.0.1,"domain":"generic","OS":"RHEL","Version":7.0},]

If that doesn't work for your real input then edit your question to include more truly representative sample input.

To skip the [ and ] lines:

$ awk '!/^[][]/{ORS=(/},/?RS:""); gsub(/[[:blank:]]+/,""); sub(/}$/,"},\n"); print}' file
{"server":"servename1","i.p":127.0.0.1,"domain":"generic","OS":"RHEL","Version":7.0},
{"server":"servename2","i.p":127.0.0.1,"domain":"generic","OS":"RHEL","Version":7.0},
{"server":"servename3","i.p":127.0.0.1,"domain":"generic","OS":"RHEL","Version":7.0},
Comments