提取系统.用Perl从JSON中获取标题



我试图从下面的JSON文件中提取System.Title值为变量。我被" Not an array reference "困住了错误。你能帮忙吗?

my $json_text = do {
open(my $json_fh, "<:encoding(UTF-8)", $filename2)
or die("Can't open $filename2": $!n");
local $/;
<$json_fh>
};
my $json = JSON->new;
my $data = $json->decode($json_text);
for ( @{$data->{fields}} ) {
print "$_->{"System.Title"}."n"";
#@witems = "$_->{System.Title}";
push @wtitle,"$_->{"System.Title"}";
chomp @wtitle;
#print "@wtitle";
}

JSON文件内容:

{
"id": 2110,
"fields": {
"System.CommentCount": 1,
"System.Title": "preprocessing with arrays",
"Microsoft.VSTS.Common.ResolvedBy": {
"displayName": "firstname, lastname",
"url": "https://dummyURL.com/4002-8be/_apis/Identities/6d91-9b75",
"_links": {
"avatar": {
"href": "https://azure.com/CARS/_apis/GraphProfile/MemberAvatars/aad.OS03ZDkxLTliN"
}
},
"id": "6d91-9b75",
"descriptor": "aad.OS03ZDkxLTliN"
},
"kanbanboard.Column": "To Do",
"kanbanboard.Column.Done": false
},
"_links": {
"fields": {
"href": "https://azure.com/CARS/ORG-ID/_apis/wit/fields"
}
},
"url": "https://azure.com/CARS/ORG-ID/_apis/wit/workItems/2110"
}

fields是一个散列引用,而不是数组引用。

my $json_text = do {
open(my $json_fh, "<:encoding(UTF-8)", $filename2)
or die("Can't open $filename2": $!n");
local $/;
<$json_fh>
};
my $json = JSON->new;
my $data = $json->decode($json_text);
print "$data->{fields}{'System.Title'}n";

这个打印:

preprocessing with arrays

我用Data::Dumper来表示$data的结构:

use Data::Dumper;
print Dumper($data);

如错误提示所示,您试图使用某个不是数组引用的内容作为数组引用。

您可以使用Data::Dumper来检查变量:

use Data::Dumper;
print $data->{fields}, "n";

这告诉你这是一个哈希引用:

哈希(0 x7fbd6d80ec90)

所以你可以访问这个散列并传递你想要的键名,例如,"System.Title"

我还会建议您始终使用use warnings;use strict;

整个代码看起来像这样(将示例JSON放在代码末尾的数据部分,这使得像这里这样的小示例更容易):

use strict;
use warnings;
use JSON;
$/ = undef;
my $json_text = <DATA>;
my $json = JSON->new;
my $data = $json->decode($json_text);
use Data::Dumper;
print $data->{fields}, "n";
print ${$data->{fields}}{'System.Title'}, "n";

__DATA__
{
"id": 2110,
"fields": {
"System.CommentCount": 1,
"System.Title": "preprocessing with arrays",
"Microsoft.VSTS.Common.ResolvedBy": {
"displayName": "firstname, lastname",
"url": "https://dummyURL.com/4002-8be/_apis/Identities/6d91-9b75",
"_links": {
"avatar": {
"href": "https://azure.com/CARS/_apis/GraphProfile/MemberAvatars/aad.OS03ZDkxLTliN"
}
},
"id": "6d91-9b75",
"descriptor": "aad.OS03ZDkxLTliN"
},
"kanbanboard.Column": "To Do",
"kanbanboard.Column.Done": false
},
"_links": {
"fields": {
"href": "https://azure.com/CARS/ORG-ID/_apis/wit/fields"
}
},
"url": "https://azure.com/CARS/ORG-ID/_apis/wit/workItems/2110"
}

最新更新