json - 将输出表转换为 JSON
问题描述
我需要在 JSON 中格式化默认的 Accel-PPP 输出,但我不是一个经验丰富的程序员,并且想要一个有效的命令来获得处理时间。我找到了这个链接https://unix.stackexchange.com/questions/243484/how-do-i-convert-the-output-of-ps1-to-json。但默认输出与上面的链接不同,如下:
ifname | username | calling-sid | rate-limit
----------+----------+-------------------+-------------
pppoe0 | joao | EC:22:80:A2:5E:D5 | 10240/1024
pppoe2 | pedro | C0:4A:00:88:E5:29 | 5120/1024
pppoe4 | maria | B0:4E:26:B1:75:7D | 5120/1024
我希望它看起来像这样:
[
{
"username":"joao",
"data":{
"ifname":"pppoe0",
"calling-sid":"EC:22:80:A2:5E:D5",
"rate-limit":"10240/1024"
}
},
{
"username":"pedro",
"data":{
"ifname":"pppoe2",
"calling-sid":"C0:4A:00:88:E5:29",
"rate-limit":"5120/1024"
}
},
{
"username":"maria",
"data":{
"ifname":"pppoe4",
"calling-sid":"B0:4E:26:B1:75:7D",
"rate-limit":"5120/1024"
}
}
]
解决方案
我制作了一个小 shell 脚本以 JSON 格式打印它:
#!/bin/bash
# Script to convert output of accel-cmd to JSON format
# Author: lfelipe
# Since: 2019-02-12
# Return of accel-cmd
ACCEL_RETURN=$(accel-cmd show sessions username,ifname,calling-sid,rate-limit,state | grep -v 'calling-sid' | grep -v '+-----' | sed 's/ //g')
# To save JSON format in string
JSON="["
# Delimiter of for
OLD_IFS=$IFS
IFS=$'\n'
# For each result
for USER in $ACCEL_RETURN
do
USERNAME=`echo ${USER} | cut -d '|' -f 1`
IFNAME=`echo ${USER} | cut -d '|' -f 2`
SID=`echo ${USER} | cut -d '|' -f 3`
RATE=`echo ${USER} | cut -d '|' -f 4`
JSON+='{'
JSON+='"username":"'${USERNAME}'",'
JSON+='"data":{'
JSON+='"ifname":"'${IFNAME}'",'
JSON+='"calling-sid":"'${SID}'",'
JSON+='"rate-limit":"'${RATE}'"'
JSON+='}'
JSON+='},'
done
# Default delimiter
IFS=$OLD_IFS
JSON+="]"
#Remove the last comma
JSON=`echo ${JSON%,*} ${JSON##*,}`
# Print JSON in string
echo "$JSON"
exit
在 CentOS 6.9 中测试并在 jsonlint 中验证 JSON
推荐阅读
- java - 无法检测到光标移动和按钮单击滞后的原因
- java - 解决 RuntimeError: PaDEL-Descriptor 遇到错误: Picked up JAVA_TOOL_OPTION in Heroku
- yarnpkg - 我可以通过 bb (bobril build) 传播“纱线安装”选项吗?
- c# - 添加显示错误消息的条件
- c# - 执行正则表达式时 CancellationSource 不起作用
- javascript - jQuery重新索引数组
- reactjs - 如何从存储中读取配置以在 react-admin 中为 DataProvider 提供 url
- youtube-api - 如何让 YouTube 主播授权我的帐户
- python - 如何在python中打开具有多个对象的非逐行json文件?
- find - 我是新手,我需要在这段代码中找到 3 个错误。您不能删除也不能插入新的代码行