Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple JSON parsing using Perl

Tags:

json

perl

I'm trying to parse the Facebook Graph API JSON results, and I'm having a bit of trouble with it.

What I was hoping to do was print the number of shares:

my $trendsurl = "https://graph.facebook.com/?ids=http://www.filestube.com"; my $json; {   local $/; #enable slurp   open my $fh, "<", $trendsurl;   $json = <$fh>; }  my $decoded_json = @{decode_json{shares}}; print $decoded_json; 
like image 598
kristin Avatar asked Mar 06 '11 12:03

kristin


People also ask

Can Perl read JSON?

Perl decode_json() function is used for decoding JSON in Perl. This function returns the value decoded from json to an appropriate Perl type.

What is Parse_json?

Interprets an input string as a JSON document, producing a VARIANT value.

What is the fastest JSON parser?

We released simdjson 0.3: the fastest JSON parser in the world is even better! Last year (2019), we released the simjson library. It is a C++ library available under a liberal license (Apache) that can parse JSON documents very fast.


1 Answers

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

#!/usr/bin/perl  use LWP::Simple;                # From CPAN use JSON qw( decode_json );     # From CPAN use Data::Dumper;               # Perl core module use strict;                     # Good practice use warnings;                   # Good practice  my $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 JSON my $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.

like image 170
Sdaz MacSkibbons Avatar answered Sep 19 '22 20:09

Sdaz MacSkibbons