繁体   English   中英

如何从Perl中的JSON响应引用数组/哈希中的数据

[英]How to reference Data in an Array/Hash from JSON Response in Perl

我正在写一些Perl代码,但我完全是菜鸟(专门用PHP和JS)。 我正在从JSON API请求中检索一些数据,我想引用该数据并为select字段构建一些HTML-Options。 但我只是想不通如何从JSON响应中引用值。

#!/bin/false

use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request;
use JSON;
use Encode;

use vars qw(@parameters $new $mode $metainfo);

use Data::Dumper qw(Dumper);

sub main
{
    if ($mode ne 'EDIT') {
        return;
    }

    my @pagetypes = _getPagetypes();
    if (scalar @pagetypes == 0 || ! defined \@pagetypes) {
        return "";
    }

    my $html = "";

    foreach (@pagetypes) {
        my $pagetype = $_;

        return Dumper @pagetypes;

        $html .= sprintf(
            '<option value="%s">%s</option>',
            $pagetype->{"identifier"},
            encode_utf8($pagetype->{"label"}),
        );
    }

    return $html;
}

##
# Get Pagetypes from API
##
sub _getPagetypes
{
    my $url = sprintf(
        "%s/page-types/",
        $ENV{'URL'}
    );

    my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => 1 });
    my $header = HTTP::Request->new(GET => $url);
    my $request = HTTP::Request->new('GET', $url, $header);
    my $response = $ua->request($request);

    my @data = decode_json($response->content);
    my @pagetypes = @data[0]->{'pageTypes'};

    return @pagetypes;
}

上面写着return Dumper $pagetypes; 编写以下输出:

$VAR1 = [
    {
        'label' => 'Projektsteckbrief',
        'identifier' => 'pagetype-profile'
    }
];

我尝试了$pagetype->{"label"}$pagetypes[0]->{"label"}等更多...但是我只是不知道如何在此处获取标签和标识符。

更新:

我尝试手动实现页面类型,并且可以通过main()方法(没有Dumper调用)正常运行:

sub _getPagetypes
{
    my @pagetypes = (
        {
            identifier => "pagetype-profile",
            label => "Projektsteckbrief",
        },
    );

    return @pagetypes;
}

更新2

所以我遇到了一个新问题……它尚未完全解决问题,但是无论如何,Bl00D4NGEL的响应是一个很大的帮助!

所以我的代码现在看起来像这样:

#!/bin/false

use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request;
use JSON;
use Encode;
use Project::Util::Api;

use vars qw(@parameters $new $mode $metainfo);

sub main
{
    if ($mode ne 'EDIT') {
        return;
    }

    my @pagetypes = _getPagetypes();
    if (scalar @pagetypes == 0 || ! defined \@pagetypes) {
        return "";
    }

    my $html = "";

    foreach my $pagetype (@pagetypes) {
        # selection will be automatically set by Imperia
        $html .= sprintf(
            '<option value="%s">%s</option>',
            $pagetype->[0]->{"identifier"},
            encode_utf8($pagetype->[0]->{"label"}),
        );
    }

    return $html;
}

##
# Get Pagetypes from API
##
sub _getPagetypes
{
    my $response = Project::Util::Api->sendRequest("/ajax/imperia/page-types/de/");
    my @pagetypes = $response->{"pageTypes"};

    return @pagetypes;
}

$new = main();

现在的问题是仅显示一项。 因此,我的foreach循环中的$pagetype看起来仍然是其中所有项目都在里面的数组,而$pagetype->[0]然后只给我数组中的第一项。

当我像这样使用for而不是foreach

for ( $a = 0 ; $a <= 10 ; $a++ ) {
    $html .= sprintf(
        '<option value="%s">%s</option>',
        @pagetypes[0]->[$a]->{"id"},
        encode_utf8(@pagetypes[0]->[$a]->{"label"}),
    );
}

我得到10个项目(共200个),但是我无法弄清楚如何获取数组@pagetypes的长度。 我尝试了以下方法:

# 500 Server error (because of long loading?)
for ( $a = 0 ; $a <= @pagetypes[0] ; $a++ ) {

my $pagetypesLength = @pagetypes;
# Only 2 items are displayed
for ( $a = 0 ; $a <= @pagetypes ; $a++ ) {
for ( $a = 0 ; $a <= $pagetypesLength ; $a++ ) {
for ( $a = 0 ; $a <= scalar @pagetypes ; $a++ ) {
for ( $a = 0 ; $a <= length @pagetypes ; $a++ ) {

更新3(最终工作)

所以最后我设法使它开始工作。 最终代码如下:

#!/bin/false

use strict;
use warnings;

use Encode;
use Project::Util::Api;

use vars qw(@parameters $new $mode $metainfo);

sub main
{
    if ($mode ne 'EDIT') {
        return;
    }

    my $items = _getData();
    if (0 == scalar @$items) {
        return "";
    }

    my $html = "";

    # $#{$items} is last index of array reference $items
    for (my $i = 0 ; $i <= $#{$items} ; $i++) {
        if (defined $items->[$i]->{"id"}) {
            # option selection will be automatically set by Imperia
            $html .= sprintf(
                '<option value="%s">%s</option>',
                $items->[$i]->{"identifier"},
                encode_utf8($items->[$i]->{"label"}),
            );
        }
    }

    return $html;
}

##
# Get Pagetypes from API
##
sub _getData
{
    my $response = Project::Util::Api->sendRequest("/ajax/imperia/page-types/de/");

    return $response->{"pageTypes"};
}

$new = main();

看起来$ pagetype变量实际上是一个数组引用(至少看起来像Dumper那样),因此应该解决的问题是:

    my $pagetype = $_;

    $html .= sprintf(

    '<option value="%s">%s</option>',
    $pagetype->[0]->{"identifier"},
    encode_utf8($pagetype->{"label"}),

    );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM