我在下面有一個 JSON 檔案,我想檢查 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"
}
我嘗試了一些方法,但我只能管理案例 1。對于其他情況,我有一個“不是哈希參考”錯誤訊息
#!/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__
uj5u.com熱心網友回復:
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' => "Cin\x{e9}ma"
},
{
'id' => 'Category::0557',
'name' => "S\x{e9}ries",
'children' => []
}
],
'type' => 'PLAY'
};
從這里可以看出,$data->{"categories"}是hashrefs 的arrayref,而不是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
}
}
uj5u.com熱心網友回復:
1.如果子陣列為空?
if (!defined($data->{categories})) { ... }
- 如果子陣列已定義并包含至少一個資料?
if (defined($data->{categories}) && @{$data->{categories}} ) { ... }
- 如果 JSON 中完全缺少 children 陣列,而我期待在這里
if (!exists $data->{categories}) { ... }
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/409720.html
標籤:
