Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert comma separated command line arguments to json in shell script

Tags:

linux

shell

I'm using below script to generate json data from comma separated values to feed zabbix. but i'm getting one extra comma symbol. please try to optimize the comma in the end line.

#/bin/bash
IFS=':, ' read -r -a array <<< "$1"
idx=0
echo {\"data\":[
while [ -n "${array[$idx]}" ]; do
        echo -n \{\"{#R_IP}\":\""${array[$idx]}"\"}
        let idx=$idx+1
        [ -n "$array[idx]}" ] && echo "," || echo
done
echo ]}
exit

input

./test.sh embimsrv.exe,emcms.exe,emcmsg.exe,emforecastsrv.exe,emgtw.exe,emguisrv.exe,emmaintag.exe,emselfservicesrv.exe,Naming_Service.exe,p_ctmce.exe,p_ctmcs.exe,p_ctmrt.exe,p_ctmtr.exe,p_ctmwd.exe

output

{"data":[
{"{#R_IP}":"embimsrv.exe"},
{"{#R_IP}":"emcms.exe"},
{"{#R_IP}":"emcmsg.exe"},
{"{#R_IP}":"emforecastsrv.exe"},
{"{#R_IP}":"emgtw.exe"},
{"{#R_IP}":"emguisrv.exe"},
{"{#R_IP}":"emmaintag.exe"},
{"{#R_IP}":"emselfservicesrv.exe"},
{"{#R_IP}":"Naming_Service.exe"},
{"{#R_IP}":"p_ctmce.exe"},
{"{#R_IP}":"p_ctmcs.exe"},
{"{#R_IP}":"p_ctmrt.exe"},
{"{#R_IP}":"p_ctmtr.exe"},
{"{#R_IP}":"p_ctmwd.exe"},
]}

like image 583
Valakatla Ashok Avatar asked Nov 16 '25 08:11

Valakatla Ashok


1 Answers

Use a proper tool, like jq, to generate your JSON.

printf '%s' "$1" | jq -R 'split(",") | map({"{#R_IP}": .}) | {data: .}'
like image 189
chepner Avatar answered Nov 19 '25 09:11

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!