2012-04-25 30 views
54

訪問JSON對象鍵我有以下的JSON對象:有空間

{ "id": "109", 
    "No. of interfaces": "4" } 

以下行工作的優良:

alert(obj.id); 
alert(obj["id"]); 

但如果鍵有空格,則我不能例如訪問它們的值

alert(obj."No. of interfaces"); //Syntax error 
alert(obj["No. of interfaces"]); //Return 'undefined' 

如何訪問其鍵名有空格的值?它甚至有可能嗎?

+9

你確定嗎? http://jsfiddle.net/hoedinie/StU38/ 它適用於我很好 – amaters 2012-04-25 07:44:15

回答

0

Pardeep耆那教的答案可以是靜態的數據是有用的,但是如果我們有什麼JSON中的數組?

例如,我們有我的價值觀和得到id字段

alert(obj[i].id); //works! 

的價值,但如果我們需要用空格鍵?

在這種情況下,下列建設可以幫助(不含塊之間的[]點):

alert(obj[i]["No. of interfaces"]); //works too!