简体   繁体   中英

How to access Json Object which has space in its name?

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

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.");
    }
}

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}});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM