programing

Perl을 사용한 간단한 JSON 해석

magicmemo 2023. 4. 1. 09:01
반응형

Perl을 사용한 간단한 JSON 해석

Facebook Graph API 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;

위의 코드 중 일부는 매우 곤혹스럽다.당신을 위해 주석을 달아 다시 썼습니다.

#!/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;줄을 설 수 있을 것 같아요.

대신 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";

    # 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 is:
{"http:\/\/www.msn.com":{"id":"http:\/\/www.msn.com","shares":331357,"comments":19}}
Number of Shares is: 331357

언급URL : https://stackoverflow.com/questions/5210523/simple-json-parsing-using-perl

반응형