【问题标题】:JSON how can I check if keys and array exists?JSON如何检查键和数组是否存在?
【发布时间】:2022-01-07 14:52:14
【问题描述】:

我有一个 JSON 文件,我想检查键是否存在,键是否为空。

我已经在下面的脚本中完成了这种检查。 但是,这里我有“孩子”,这是一个空数组。 如何查看该数组是否存在以及该数组是否为空?

这里是 JSON 示例:

{
  "id": "Store::STUDIO",
  "name": "Studio",
  "categories": [
    {
      "id": "Category::556",
      "name": "Cinéma",
      "children": []
    },
    {
      "id": "Category::557",
      "name": "Séries",
      "children": []
    }
  ],
  "images": [
    {
      "format": "iso",
      "url": "http://archive.ubuntu.com/ubuntu/dists/bionic-updates/main/installer-amd64/current/images/netboot/mini.iso",
      "withTitle": false
    }
  ],
  "type": "PLAY"
}

这是脚本:

#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use JSON qw( decode_json );
use JSON qw( from_json );

# JSON file 
my $json_f = '/home/test';

# Variable
my $curl_cmd = "curl -o /dev/null --silent -Iw '%{http_code}'";

# JSON text
my $json_text = do {
        open (TOP, "<", $json_f);
        local $/;
        <TOP>
};


my $decoded = from_json($json_text);

# Display value provider if exist
my $provider =  $decoded->{"categories"}[0]{"provider"};
print $provider, "\n" if scalar $provider;

# Display value children if exist
my @child =  $decoded->{"categories"}[0]{"children"};
print $child[0], "\n" if scalar @child;

# Checking an url is exist
my $url_src = $decoded->{"images"}[0]{"url"};
my $http_res = qx{$curl_cmd $url_src}; # Checking if URL is correct

# Display categories with others values
my @categories = @{ $decoded->{'categories'} };
        foreach my $f ( @categories ) {
        print $decoded->{"id"} . "|" . $f->{"id"} . "|" . $f->{"name"} . "|" . $http_res . "\n";
}

【问题讨论】:

    标签: json perl curl


    【解决方案1】:

    在您的代码中,@child 是一个数组数组。取消引用数组。变化:

    my @child =  $decoded->{"categories"}[0]{"children"};
    

    到:

    my @child =  @{ $decoded->{"categories"}[0]{"children"} };
    

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 2016-08-07
      • 2012-10-21
      • 2022-11-24
      相关资源
      最近更新 更多