Hello, I am having a slight issue in Perl 5.2. I've used libjson-perl for a few years and written many things which used it to decode Json from websites. I am now in the process of writing a bot for the chat app Discord which uses a Json api, much like other places I've written bots for previously. I know my code is right, or at least should be, yet I am getting the "not a hash reference error." Here is the output I am getting in my terminal.
$VAR1 = [ { 'mentions' => [], 'author' => { 'avatar' => '035a793a88596c440cb0434f272d8f3 +c', 'discriminator' => '4559', 'id' => '159495601208164353', 'username' => 'MiyakoProductions' }, 'embeds' => [], 'channel_id' => '193239098226376705', 'tts' => bless( do{\(my $o = 0)}, 'JSON::XS::Boolean' ), 'mention_roles' => [], 'mention_everyone' => $VAR1->[0]{'tts'}, 'content' => 'so i wrote a simple script to pull each one +automatically', 'id' => '233412710220562432', 'type' => 0, 'pinned' => $VAR1->[0]{'tts'}, 'edited_timestamp' => undef, 'timestamp' => '2016-10-06T02:18:46.715000+00:00', 'attachments' => [] } ]; Not a HASH reference at discord.pl line 70.
My code itself is:
sub getMessages($) { my $apiUrl = $baseUrl . "channels/" . $_[0] . "/messages?limit=1"; print "$apiUrl\n"; my $discordClient = WWW::Mechanize->new( agent => 'DiscordBot (Lib +Discord-Perl5 1)' ); $discordClient->add_header('Authorization' => "$authToken"); my $clientConnected = eval { $discordClient->get($apiUrl, 'Content +-Type' => 'application/json'); }; if (! $clientConnected ) { errorCon(); } else { # Set values when connection is successful our $apiContent = $discordClient->content; #print Dumper($apiContent) . "\n"; my @apiJson = decode_json( $apiContent ); print "Pretty Response:\n" . Dumper( @apiJson ) . "\n"; my $msgID = $apiJson[0]->{'id'}; my $msgAuthor = $apiJson[0]->{'author'}->{'username'}; my $msgContent = $apiJson[0]->{'content'}; if ($msgID > $lastMsgID) { print "<$msgAuthor> $msgContent\n"; $lastMsgID = $msgID; } } } sub errorCon { print "Error: Unable to connect to Discord!\n"; }
The response is generally 50 messages long, however I limit it to 1 message for ease of parsing and debugging. Therefore, I am treating the response first as an array, and yes I have tried to foreach through it. After treating it as an array I do the normal syntax to retrieve the value of a key. Is there something I am missing?
In reply to Perplexing JSON decoding issue. by Miyako
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |