2011-03-06 14 views
33

Facebook Graph API JSON sonuçlarını ayrıştırmaya çalışıyorum ve bununla ilgili biraz sorun yaşıyorum. Yukarıdaki kod bazıları son derece şaşırtıcı olduğunuPerl kullanarak basit JSON ayrıştırma

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; 

cevap

105

:

Ne yapmak umuyordum hisse sayısını yazdırmak oldu. Sadece sizin için ek açıklamalarla yeniden yazdım.

#!/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"; 

Çalıştırın ve çıkışı kontrol edin. Neler olduğunu anladığınızda print Dumper $decoded_json; hattını yorumlayabilirsiniz.

+4

Büyük 1 Yanıtlayıcılar se. 15 yıl içinde fazla bir kod yazmamıştım, bu yüzden kapsamlı örneğiniz perl'de hızlanmama gerçekten yardımcı oldu. – fool4jesus

2

Bunun yerine CURL komutunu kullanmaya ne dersiniz? (P.S .: Bu Windows üzerinde çalışıyor; Unix sistemleri için CURL değişiklikleri yapıyor).

$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 output 
    if ($exec=~/"shares":?/) 
    { 
     print "Output is::: \n$exec\n\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" 
    } 

ÇIKIŞ:


Çıktı olduğunu ::: { "http://www.msn.com": { "id": "http: // www. msn.com", "hisse": 331357, "yorum": 19}}

Hisselerin sayısı: 331357


+0

CURL kullanımı tam olarak perl kullanmıyor. – Jacob