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"......
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"......
Share Improve this question edited Sep 9, 2011 at 13:15 Juozas Kontvainis 9,5976 gold badges57 silver badges66 bronze badges asked Oct 28, 2010 at 11:57 SriSri 331 gold badge1 silver badge4 bronze badges 1- 3 In which programming language? – Marcelo Cantos Commented Oct 28, 2010 at 12:00
2 Answers
Reset to default 13var 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.");
}
}
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}});
}