es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Cómo puedo verificar si existen claves y arreglos en JSON?

Tengo un archivo JSON y quiero verificar si existen o no las claves, si las claves están vacías o no.

Ya he hecho este tipo de verificación en el siguiente script.
Pero aquí tengo “children” que es un array vacío.
¿Cómo puedo ver si este array existe o no y si está vacío o no?

Aquí se muestra el ejemplo 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"
}

Aquí está el script:

“`
#!/usr/bin/perl

use strict;
use warnings;
use utf8;
use JSON qw( decode_json );
use JSON qw( from_json );

<h1>JSON file</h1>

my $json_f = '/home/test';

<h1>Variable</h1>

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

<h1>JSON text</h1>

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

my $decoded = from_json($json_text);

<h1>Display value provider if exist</h1>

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

<h1>Display value children if exist</h1>

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

<h1>Checking an url is exist</h1>

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

<h1>Display categories with others values</h1>

my @categories = @{ $decoded->{'categories'} };
foreach my $f ( @categories ) {
print $decoded->{"id"} . "|" . $f->{"id"} . "|" . $f->{"name"} . "|" . $http_res . "\n";
}
“`

Tags:  , ,

Answer

  1. Avatar for davy.ai

    Para comprobar si el array “children” existe o no, y si está vacío o no, puedes usar el siguiente código:

    # Comprobar si existe la clave "children"
    if (exists $decoded->{"categories"}[0]->{"children"}) {
      # Comprobar si el array "children" está vacío
      if (@{ $decoded->{"categories"}[0]->{"children"} } == 0) {
        print "El array 'children' existe pero está vacío.\n";
      }
      else {
        print "El array 'children' existe y no está vacío.\n";
      }
    }
    else {
      print "La clave 'children' no existe.\n";
    }
    

    Este código primero verifica si la clave “children” existe en el primer elemento del array “categories”. Si existe, comprueba si el array está vacío utilizando la notación “@{}” para acceder al array y verificar su tamaño. Si el array no está vacío, imprime que el array existe y no está vacío. Si el array está vacío, imprime que el array existe pero está vacío. Si la clave “children” no existe, imprime que la clave no existe.

Comments are closed.