How to access a Json object that has a place in its name?

Find below json answer ...

{"Object": {"PET ANIMALS":[{"id":1,"name":"Dog"}, {"id":2,"name":"Cat"}], "Wild Animals":[{"id":1,"name":"Tiger"}, {"id":2,"name":"Lion"}] } } 

In the answer above, what is the way to find the length of "FOOD ANIMALS" and "WILD ANIMALS" ...

+3
source share
2 answers
 var json = /* your JSON object */ ; json["Object"]["PET ANIMALS"].length // returns the number of array items 

Using a loop to print the number of elements in arrays:

 var obj = json["Object"]; for (var o in obj) { if (obj.hasOwnProperty(o)) { alert("'" + o + "' has " + obj[o].length + " items."); } } 
+12
source

You did not 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}}); } 
+1
source

Source: https://habr.com/ru/post/1403384/


All Articles