首页 > 解决方案 > 将输出表转换为 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"
      }
   }
]

标签: json

解决方案


我制作了一个小 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


推荐阅读