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
1
  • 3
    How is the JSON supposed to look? What are the names of the fields? Take a look at this: stedolan.github.io/jq Commented Nov 26, 2018 at 9:58

2 Answers 2

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"}
0
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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.