Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access json object key with space [duplicate]

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?

Here is an example of my json file

{"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","Jack 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);
}
});
like image 414
user3210416 Avatar asked May 13 '14 17:05

user3210416


People also ask

Can JSON object keys have spaces?

Whitespace (Space, Horizontal tab, Line feed or New line or Carriage return) does not matter in JSON. It can also be minified with no affect to the data. Object literal names MUST be lowercase (ie – null, false, true etc).

How can I get the key-value in a JSON object?

To get a JSON object's key and value in JavaScript, we can use the JSON. parse method to parse the JSON object string into a JavaScript object. Then we can get a property's value as we do with any other JavaScript object.

How does JSON handle space in value?

If you want to use " in your String use escape character which is most often \ . Examples: "Deutchland" , "Costa Rica" , "He said \"whatever\" " . Integer value can be without quotes, but it's a good practice to quote them and later cast those Strings to proper numeric types.

Can object keys have spaces?

Object Keys Are Strings Object keys with underscores and camelCase (no spaces) don't require the bracket syntax, but object keys with spaces and hyphens do. You may prefer the code readability of the . dot syntax, in which case you'll want to avoid spaces in your object keys: you might write object.


1 Answers

Change

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

to

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

Read Working with objects

like image 73
Denys Séguret Avatar answered Oct 24 '22 20:10

Denys Séguret