Perl检查JSON中对象是否定义、丢失或为空的最佳方法是什么



我下面有一个JSON文件,我想检查的3种状态

在阵列"内";类别";我有另一个数组";儿童";当前为空

我该怎么做才能知道

  1. 如果子数组为null
  2. 如果子数组已定义并且至少包含一个数据
  3. 如果JSON中完全缺少children数组,而我原本希望在这里

下面是JSON文件

{
"id": "Store::REZZ",
"name": "Rezz",
"categories": [
{
"id": "Category::0556",
"name": "Cinéma",
"children": []
},
{
"id": "Category::0557",
"name": "Séries",
"children": []
}
],
"images": [
{
"format": "logo",
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/1920px-Google_2015_logo.svg.png",
"withTitle": false
}
],
"type": "PLAY"
}

我试了一些办法,但我只能应付第一种情况。对于其他情况;不是哈希引用";错误消息

#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use JSON qw( decode_json );
use JSON qw( from_json );
# JSON file 
my $json_f = '/home/test';
# JSON text
my $json_text = do {
open (TOP, "<", $json_f);
local $/;
<TOP>
};
my $data = from_json($json_text);
my @tags = @{ $data->{"categories"}{"children"} };
if (@tags) { 
foreach (@tags) {
say $_->{"name"};
say "1. array is ok and contains data";
}   
} elsif (@tags == 0) {
say "3. array is empty";
} else {
say "2. array is missing";
}
__END__

Data::Dumper将使您能够可视化JSON转换为的perl数据结构

$VAR1 = {
'images' => [
{
'withTitle' => bless( do{(my $o = 0)}, 'JSON::PP::Boolean' ),
'url' => 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/1920px-Google_2015_logo.svg.png',
'format' => 'logo'
}
],
'id' => 'Store::REZZ',
'name' => 'Rezz',
'categories' => [
{
'children' => [],
'id' => 'Category::0556',
'name' => "Cinx{e9}ma"
},
{
'id' => 'Category::0557',
'name' => "Sx{e9}ries",
'children' => []
}
],
'type' => 'PLAY'
};

从中可以看出,$data->{"categories"}是hashref的数组,而不是hashref本身。

您可以对其元素进行迭代:

foreach my $cat (@{$data->{categories}}) {
if (!exists $cat->{children}) {
# No children element
} elsif (@{$cat->{children}} == 0) {
# Empty array
} else {
# Has at least element in the array
}
}

1.如果子数组为null?

if (!defined($data->{categories})) { ... }
  1. 是否定义了子数组并至少包含一个数据
if (defined($data->{categories}) && @{$data->{categories}} ) { ... }
  1. 如果JSON中完全缺少children数组,而我本来希望在这里
if (!exists $data->{categories}) { ... }

相关内容

最新更新