javascript 如何使用空格访问json对象键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23638413/
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-28 01:16:16  来源:igfitidea点击:

How to access json object key with space

javascriptjqueryjson

提问by user3210416

I have a json file and the key of almost each object has a space between them, for their first and last name. So every time I try and call the value of that key it says 'undefined. How do I get the values to show?

我有一个 json 文件,几乎每个对象的键之间都有一个空格,用于他们的名字和姓氏。因此,每次我尝试调用该键的值时,它都会显示“未定义”。我如何获得要显示的值?

Here is an example of my json file

这是我的 json 文件的示例

{"Wojciech Szczesny":"yes","Lukasz Fabianski":"no","Emiliano Viviano":"no","Olivier Giroud":"yes","Per Mertesacker":"yes","Bacary Sagna":"yes","Laurent Koscielny":"no","Santi Cazorla":"yes","Mikel Arteta":"yes","Mesut \u00d6zil":"no","Kieran Gibbs":"yes","Aaron Ramsey":"no","Hyman Wilshere":"no","Mathieu Flamini":"yes","Tomas Rosicky":"yes","Lukas Podolski":"yes","Nacho Monreal":"no","Theo Walcott":"no","Thomas Vermaelen":"yes","Carl Jenkinson":"no","Alex Oxlade-Chamberlain":"no","Serge Gnabry":"no","Kim Kallstrom":"no","Nicklas Bendtner":"no","Abou Diaby":"no","Park Chu-Young":"no","Emmanuel Frimpong":"no","Yaya Sanogo":"no","Ryo Miyaichi":"no","Hector Bellerin":"no","Chuba Akpom":"no","Isaac Hayden":"no","Gideon Zelalem":"no"}

Here is my code

这是我的代码

$.ajax({
url:'ars.json',
dataType:'json',
cache: false,
success: function(data) {
var count = 0;
arrayTesting.push(Object.getOwnPropertyNames(data[0]));
for(var key in data) {
            //This line does not run at all
    if(data[key].Per Mertesacker){
        count++;
    }else{}

}
    //Nothing prints out in the console
    console.log(data[key].Per Mertesacker);
}
});

回答by Denys Séguret

Change

改变

console.log(data[key].Per Mertesacker);

to

console.log(data[key]['Per Mertesacker']);

Read Working with objects

阅读使用对象