Converter arquivo de texto para JSON

1

Iniciante aqui, espero que você possa me direcionar para o caminho certo. Usando o curl, recebo algumas informações estatísticas do meu roteador TP-Link. Eu coloquei essa informação em um arquivo de texto. No entanto, preciso dessas informações no formato JSON para poder usá-las em outro lugar. O formato do arquivo de texto é assim:

[0,0,0,0,0,0]0
enable=1
interval=10
action=0
[1,0,0,0,0,0]1
ipAddress=3232235848
macAddress=EC:0E:C4:4F:XX:XX
totalPkts=201
totalBytes=22914
currPkts=0
currBytes=0
currIcmp=0
currUdp=0
currSyn=0
currIcmpMax=0
currUdpMax=15
currSynMax=0
[2,0,0,0,0,0]1
ipAddress=3232235829
macAddress=00:16:E8:22:XX:XX
totalPkts=972
totalBytes=98730
currPkts=0
currBytes=0
currIcmp=0
currUdp=0
currSyn=0
currIcmpMax=0
currUdpMax=14
currSynMax=4
[3,0,0,0,0,0]1
ipAddress=3232235842
macAddress=70:14:A6:8B:XX:XX
totalPkts=154566
totalBytes=15116490
currPkts=0
currBytes=0
currIcmp=0
currUdp=0
currSyn=0
currIcmpMax=9
currUdpMax=58
currSynMax=60

Eu preciso de um JSON algo como:

{"ipAddress" : "3232235848",
"macAddress" : "EC:0E:C4:4F:XX:XX",
"totalPkts" : "201",
"totalBytes" : "22914",
"currPkts" : "0",
"currBytes" : "0",
"currIcmp" : "0",
"currUdp" : "0",
"currSyn" : "0",
"currIcmpMax" : "0",
"currUdpMax" : "15",
"currSynMax" : "0"}
{"ipAddress" : "3232235829", ...

Você poderia me mostrar a maneira mais eficiente de fazer isso? Eu prefiro um script bash se for possível? Tentei colocar "| jq -R -s-c 'split (" \ n ")'" no final do comando curl, mas depois parece que:     {"ipAddress = 3232235848", "macAddress = EC: 0E: C4: 4F: XX: XX" ...

    
por febalci 04.06.2017 / 16:44

2 respostas

1
perl -lne 'BEGIN{*1 = sub {print q<{>, join(",\n", splice @A, 0, @A), q<}>}}
   next if $. == 1;
   /^\[(?:\d+,?)+\]\d+$/ and &1,next;
   push @A, join q/ : /, map qq/"$_"/, split /=/;
   eof && &1;
' yourfile
    
por 04.06.2017 / 18:37
0

sed hack:

sed -E -e 's/\[([0-9],){5}[0-9]\][0-9]+/}{/g; s/([[:alnum:]]+)=([[:alnum:]]+)/"" : "",/; 
           s/,\n}/}/;  1s/.*/{/; $s/.*/&}/' yourfile | sed -Ez 's/,\n?}/ }\n/g'

A saída:

{
"enable" : "1",
"interval" : "10",
"action" : "0" }
{
"ipAddress" : "3232235848",
"macAddress" : "EC",:0E:C4:4F:XX:XX
"totalPkts" : "201",
"totalBytes" : "22914",
"currPkts" : "0",
"currBytes" : "0",
"currIcmp" : "0",
"currUdp" : "0",
"currSyn" : "0",
"currIcmpMax" : "0",
"currUdpMax" : "15",
"currSynMax" : "0" }
{
"ipAddress" : "3232235829",
"macAddress" : "00",:16:E8:22:XX:XX
"totalPkts" : "972",
"totalBytes" : "98730",
"currPkts" : "0",
"currBytes" : "0",
"currIcmp" : "0",
"currUdp" : "0",
"currSyn" : "0",
"currIcmpMax" : "0",
"currUdpMax" : "14",
"currSynMax" : "4" }
{
"ipAddress" : "3232235842",
"macAddress" : "70",:14:A6:8B:XX:XX
"totalPkts" : "154566",
"totalBytes" : "15116490",
"currPkts" : "0",
"currBytes" : "0",
"currIcmp" : "0",
"currUdp" : "0",
"currSyn" : "0",
"currIcmpMax" : "9",
"currUdpMax" : "58",
"currSynMax" : "60" }
    
por 04.06.2017 / 23:40