tags:

views:

41

answers:

2

Hi,

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"......

+1  A: 
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.");
    }
}
Šime Vidas
Is there anyway to get the length using indexes. for e.g. json["Object"][0].length instead of json["Object"]["PET ANIMALS"].length
Sri
@Sri Interesting question. I'm not sure, but I think not. Objects are collections of **unordered** properties, so there is no order based on which you could get the first, second, third, etc. property. But you may use a loop - I updated my answer.
Šime Vidas
A: 

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}});
}
David Dorward
oh thanks.i wanted that in javascript
Sri