Simple JSON parsing using Perl Simple JSON parsing using Perl json json

Simple JSON parsing using Perl


Some of the code above is extremely puzzling. I've just rewritten it with annotations for you.

#!/usr/bin/perluse LWP::Simple;                # From CPANuse JSON qw( decode_json );     # From CPANuse Data::Dumper;               # Perl core moduleuse strict;                     # Good practiceuse warnings;                   # Good practicemy $trendsurl = "https://graph.facebook.com/?ids=http://www.filestube.com";# open is for files.  unless you have a file called# 'https://graph.facebook.com/?ids=http://www.filestube.com' in your# local filesystem, this won't work.#{#  local $/; #enable slurp#  open my $fh, "<", $trendsurl;#  $json = <$fh>;#}# 'get' is exported by LWP::Simple; install LWP from CPAN unless you have it.# You need it or something similar (HTTP::Tiny, maybe?) to get web pages.my $json = get( $trendsurl );die "Could not get $trendsurl!" unless defined $json;# This next line isn't Perl.  don't know what you're going for.#my $decoded_json = @{decode_json{shares}};# Decode the entire JSONmy $decoded_json = decode_json( $json );# you'll get this (it'll print out); comment this when done.print Dumper $decoded_json;# Access the shares like this:print "Shares: ",      $decoded_json->{'http://www.filestube.com'}{'shares'},      "\n";

Run it and check the output. You can comment out the print Dumper $decoded_json; line when you understand what's going on.


How about using CURL command instead? (P.S.: This is running on Windows; make CURL changes for Unix systems).

$curl=('C:\\Perl64\\bin\\curl.exe -s http://graph.facebook.com/?ids=http://www.filestube.com');$exec=`$curl`;print "Output is::: \n$exec\n\n";# match the string "shares": in the CURL outputif ($exec=~/"shares":?/) {     print "Output is:\n$exec\n";    # string after the match (any string on the right side of "shares":)    $shares=$';     # delete all non-Digit characters after the share number    $shares=~s/(\D.*)//;     print "Number of Shares is: ".$shares."\n";} else {    print "No Share Information available.\n"}

OUTPUT:

Output is:{"http:\/\/www.msn.com":{"id":"http:\/\/www.msn.com","shares":331357,"comments":19}}Number of Shares is: 331357