我有一个运行的命令,它提供如下输出:
{
"endpointApplications": {
"App_Name": {
"connectionState": "Disconnected",
"connectionTime": "No connection was established",
"linkAttributes": {
"ackSettings": {
"dataAckEnabled": "true",
"dataAckTimeout": "5000",
"dataNakRetryLimit": "0",
"retransmitDelay": "500"
},
"keepAliveSettings": {
"keepAliveAckTimeout": "5000",
"keepAliveInterval": "30000"
},
"logTraffic": "false",
"port": "9999",
"role": "server"
},
"protocol": "snmp"
}
},
"queueStats": {}
}
我需要输出如下所示:
{"endpointApplications": {"app_name": {"connectionState": "Disconnected","connectionTime": "No connection was established","linkAttributes": {"ackSettings":{"dataAckEnabled": "true","dataAckTimeout": "5000","dataNakRetryLimit": "0","retransmitDelay": "500"},"keepAliveSettings":{"keepAliveAckTimeout": "5000","keepAliveInterval": "30000"},"logTraffic": "false","port": "9999","role": "server"},"protocol": "snmp"}},"queueStats":{}}
我尝试使用awk和sed结合不同的参数,但我无法在不丢失JSON格式的情况下开始工作。
答案 0 :(得分:10)
你应该使用jq这样的东西:
jq -c . input.txt
使用sed
& tr
:
sed -e 's/^ *//' < input.txt | tr -d '\n'
虽然我建议使用专为操作JSON而设计的jq
。对于JSON,jq
与sed
类似。使用sed
/ awk
/ etc以文本方式操作JSON不能保证生成语义上等效的JSON。
答案 1 :(得分:7)
jq
或任何其他json
识别工具最适合json文件操作。但此处基于awk
的解决方案。
awk -v RS= '{$1=$1}1' input.json
{ "endpointApplications": { "App_Name": { "connectionState": "Disconnected", "connectionTime": "No connection was established", "linkAttributes": { "ackSettings": { "dataAckEnabled": "true", "dataAckTimeout": "5000", "dataNakRetryLimit": "0", "retransmitDelay": "500" }, "keepAliveSettings": { "keepAliveAckTimeout": "5000", "keepAliveInterval": "30000" }, "logTraffic": "false", "port": "9999", "role": "server" }, "protocol": "snmp" } }, "queueStats": {} }
注意:此解决方案主要针对没有像jq
这样的工具的旧系统,并且由于某些原因没有机会安装它们。