javascript 如何访问名称中有空格的 Json 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4042646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:15:13 来源:igfitidea点击:
How to access Json Object which has space in its name?
提问by Sri
Find below the json response...
在 json 响应下方找到...
{"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"......
在上面提到的响应中,如何找到“PET ANIMALS”和“Wild ANIMALS”的长度......
回答by ?ime Vidas
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.");
}
}
回答by Quentin
You didn't specify a language, so here is an example in Perl:
您没有指定语言,所以这里有一个 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}});
}

