Marisa Giancarla Marisa Giancarla - 1 month ago 6
JSON Question

How to parse JSON/REST data from server using Perl

Im trying to parse out JSON output from the server using Perl. The connection and downloading of the REST data is ok, I just need help parsing the returned data. Here is the snippet for my code:

my $response = HTTP::Tiny->new->get($SERVER_ADDR);
if ($response->{success})
my $html = $response->{content};
@LINES = split /\n/, $html;
print("Lines: '@LINES'\n"); # ZZZ
my $decoded_json = decode_json( $html );
print Dumper $decoded_json;
print "Failed: $response->{status} $response->{reasons}";

And here is the results:

Lines: '{"players":[{"currentlyOnline":false,"timePlayed":160317,"name":"MarisaG","lastPlayed":1474208741470}]}'
$VAR1 = {
'players' => [
'currentlyOnline' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ),
'timePlayed' => 160317,
'lastPlayed' => '1474208741470',
'name' => 'MarisaG'

There will be multiple entries under the "players" for each player logged in right now. Any tips?


I'm not really sure what you're asking. You have successfully parsed the JSON by by calling decode_json(). You now have a data structure in $decoded_json. Your call to Dumper() shows the structure of that data. It's a hash reference with a single key, players. The value associated with that key is an array reference. Each element in the referenced array is another hash.

So, for example, you could print all of the players' names with code like this.

foreach (@{ $decoded_json->{players} }) {
  say $_->{name};