Seth
Seth

Reputation: 364

JSON how can I check if keys and array exists?

I have a JSON file, and I want to check if keys exists or not, if keys are empty or not.

I've already done this kind of check in the script below. But, here I have "children" which is an empty array. How can I see if this array exists or not and if this array is empty or not?

Here the JSON sample:

{
  "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"
}

Here is the script:

#!/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";
}

Upvotes: 1

Views: 474

Answers (1)

toolic
toolic

Reputation: 62037

In your code, @child is an array of arrays. Dereference the array. Change:

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

to:

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

Upvotes: 2

Related Questions