使用Perl进行简单的JSON解析 [英] Simple JSON parsing using Perl

查看:119
本文介绍了使用Perl进行简单的JSON解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析Facebook 图形API JSON结果,我我有点麻烦.

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;

推荐答案

上面的某些代码非常令人困惑.我刚刚为您重写了注释.

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

运行它并检查输出.当您了解发生了什么情况时,可以注释掉print Dumper $decoded_json;行.

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

这篇关于使用Perl进行简单的JSON解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆