0

I have this output in the following and I am trying to convert it to JSON api format. I want to know how can I do it.

 rock64@rockpro64:~$ sh MACscript.sh 
 eth0
   11:1d:11:11:11:1d
 lo
   00:00:00:00:00:00

Do I have to use python script or can I do it using shell script?

This is my MACshell script:

 rock64@rockpro64:~$ cat MACscript.sh 
 !/bin/bash
 getmacifup.sh: Print active NICs MAC addresses
 D='/sys/class/net'
 for nic in $( ls $D )
 do
   echo $nic
   if  grep -q unknown $D/$nic/operstate
   then
    echo -n '   '
    cat $D/$nic/address
  fi
 done
  • 2
    How is the JSON supposed to look? What are the names of the fields? Take a look at this: stedolan.github.io/jq – Panki Nov 26 '18 at 9:58
3

With plain bash you could do:

json=$(
    sh MACscript.sh | {
        pairs=()
        while read interface; read ether; do
            pairs+=("\"$interface\":\"$ether\"")
        done
        IFS=,
        echo "{${pairs[*]}}"
    }
)
echo "$json"

outputs

{"eth0":"11:1d:11:11:11:1d","lo":"00:00:00:00:00:00"}
  • Wow, this solution is just perfect. Thank you – Rakib Fiha Nov 27 '18 at 2:27
0

you can use various ways to get your json values. bash, python,perl,.....
you can find useful posts about these in this website. however here is an example:

  arr1=($( ls /sys/class/net))
  arr2=($( cat /sys/class/net/*/address ))

  vars1=(${arr1[@]})
  vars2=(${arr2[@]})
  len=${#arr1[@]}

  printf "{\n"
  printf "\t"'"data"'":[\n"

  for (( i=0; i<len; i+=1 ))
  do
  printf "\t{  "'"{#interface}"'":\"${vars1[i]}\",\t"'"{#address}"'":\"${vars2[i]}\"  
  }"

  if [ $i -lt $((len-1)) ] ; then
    printf ",\n"
  fi
  done
  printf "\n"
  printf "\t]\n"
  printf "}\n"
  echo  

output:

{
    "data":[
    {  "{#interface}":"eth0",       "{#address}":"00:50:56:a9:c0:81"  },
    {  "{#interface}":"lo", "{#address}":"00:00:00:00:00:00"  }
    ]
}

and you can use this website to validate your json: https://codebeautify.org/online-json-editor

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.