Reputation: 33
Find below the json response...
{"Object":
{"PET ANIMALS":[{"id":1,"name":"Dog"},
{"id":2,"name":"Cat"}],
"Wild Animals":[{"id":1,"name":"Tiger"},
{"id":2,"name":"Lion"}]
}
}
In the above mentioned response, what is the way to find the length of "PET ANIMALS" and "Wild ANIMALS"......
Upvotes: 3
Views: 11155
Reputation: 185953
var json = /* your JSON object */ ;
json["Object"]["PET ANIMALS"].length // returns the number of array items
Using a loop to print the number of items in the arrays:
var obj = json["Object"];
for (var o in obj) {
if (obj.hasOwnProperty(o)) {
alert("'" + o + "' has " + obj[o].length + " items.");
}
}
Upvotes: 13
Reputation: 943936
You didn't specify a language, so here is an example in Perl:
#!/usr/bin/perl
use strict;
use warnings;
use v5.10;
use JSON::Any;
use File::Slurp;
my $json = File::Slurp::read_file('test.json');
my $j = JSON::Any->new;
my $obj = $j->jsonToObj($json);
say scalar @{$obj->{'Object'}{'PET ANIMALS'}};
# Or you can use a loop
foreach my $key (keys %{$obj->{'Object'}}) {
printf("%s has %u elements\n", $key, scalar @{$obj->{'Object'}{$key}});
}
Upvotes: 1