2011-03-06 3 views
33

Facebook Graph API JSON 결과를 구문 분석하려고하는데 문제가 있습니다. 위의 코드 중 일부는 매우 수수께끼입니다Perl을 사용한 간단한 JSON 구문 분석

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; 

답변

105

:

는 내가 뭘 바라고하는 주식의 수를 인쇄했다. 방금 주석 달기로 다시 작성했습니다.

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

실행하여 출력을 확인하십시오. 진행 상황을 이해하면 print Dumper $decoded_json; 행을 주석으로 처리 할 수 ​​있습니다.

+4

대 한 respon se. 필자는 15 년 동안 많은 펄 코드를 작성하지 않았기 때문에 철저한 예제를 통해 펄의 속도를 높일 수있었습니다. – fool4jesus

2

대신 CURL 명령을 사용하는 것이 어떻습니까? (P.S .: Windows에서 실행 중이며 Unix 시스템에서는 CURL을 변경합니다.)

$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" 
    } 

출력 :


출력이 ::: { "http://www.msn.com": { "ID": "HTTP : // WWW. msn.com ","주 ": 331357,"의견 ": 19}}

주식의 번호는 : 331,357


+0

CURL을 사용하는 것이 perl을 정확하게 사용하지 않습니다. – Jacob