Last active
March 17, 2019 21:19
-
-
Save sidey79/6b04dc5b7732b49acc75d541cd2b2f09 to your computer and use it in GitHub Desktop.
Perl JSON example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main; | |
use strict; | |
use warnings; | |
use Time::HiRes qw(gettimeofday); | |
use Data::Dumper qw(Dumper); | |
use JSON qw (decode_json encode_json); | |
my $jsonStr='[ | |
{ | |
"id": "0.2", | |
"name": "generic", | |
"data": [ | |
{ | |
"dmsg": "-", | |
"protocol_info": "x", | |
"raw": "MS;P1=-2140;P2=309;P3=-4690;P4=-9695;D=2421232323232121232123232321212121212121212123212121232121;CP=2;SP=4;R=211;m1;", | |
"state": "no info", | |
"user": "unknown" | |
} | |
] | |
}, | |
{ | |
"id": "0", | |
"name": "generic", | |
"data": [ | |
{ | |
"dmsg": "-", | |
"protocol_info": "x", | |
"raw": "MS;P1=-7949;P2=492;P3=-1978;P4=-3970;D=21232423232424242423232323232324242423232323232424;CP=2;SP=1;R=245;O;", | |
"state": "no info", | |
"user": "unknown" | |
} | |
] | |
}, | |
{ | |
"id": "0", | |
"name": "generic", | |
"data": [ | |
{ | |
"dmsg": "-", | |
"protocol_info": "x", | |
"raw": "MS;P1=-7949;P2=492;P3=-1978;P4=-3970;D=21232423232424242423232323232324242423232323232424;CP=2;SP=1;R=245;O;", | |
"state": "no info", | |
"user": "unknown" | |
}, | |
{ | |
"dmsg": "-", | |
"protocol_info": "x", | |
"raw": "MS;P1=-7949;P2=492;P3=-1978;P4=-3970;D=21232423232424242423232323232324242423232323232424;CP=2;SP=1;R=245;O;", | |
"state": "no info", | |
"user": "unknown" | |
} | |
] | |
} | |
] | |
'; | |
my @decoded_json = @{decode_json($jsonStr)}; | |
print "foreach version:\n"; | |
foreach my $entry (@decoded_json) | |
{ | |
print "--------------------------\n"; | |
foreach (@{${$entry}{data}}) | |
{ | |
#print Dumper($_->{user})."\n"; | |
#my @data=@{$_}; | |
printf "%s(%s): from: %s\trmsg=%s -> dmsg=%s\n" , ${$entry}{name}, ${$entry}{id}, ${$_}{user},${$_}{raw},${$_}{dmsg}; | |
} | |
} | |
print "\n\nfor loop with index version:\n"; | |
for my $i (0 .. $#decoded_json) | |
{ | |
print "--------------------------\n"; | |
for my $j (0 .. $#{$decoded_json[$i]{data}}) | |
{ | |
#print Dumper($_->{user})."\n"; | |
#my @data=@{$_}; | |
printf "%s(%s): from: %s\trmsg=%s -> dmsg=%s\n" , $decoded_json[$i]{name}, $decoded_json[$i]{id}, $decoded_json[$i]{data}[$j]{user},$decoded_json[$i]{data}[$j]{raw},$decoded_json[$i]{data}[$j]{dmsg}; | |
} | |
} | |
exit; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will generate the following output: