2016-06-13 145 views
0

如何在jsp中創建json對象?如何在jsp中創建json對象?

var jsonObj = { 
    "firstname": "test", 
    "lastName": "test", 
    "email": "test", 
    "mobile": "test", 
    "place": "test", 
    "country": "test" 
}; 

alert(jsonObj.length); 

這會打印「undefined」的長度。


var json = {"person": 
    { 
     "p1": 
      {"home": 
       {"address":0, 
       "phoneNumber":0 
       }, 
      "office": 
       {"address":0, 
       "phoneNumber":0 
       } 
      }, 

     "p2": 
      {"home": 
       {"address":0, 
       "phoneNumber":0 
       }, 
      "office": 
       {"address":0, 
       "phoneNumber":0 
       } 
      }, 

     "p3": 
      {"home": 
       {"address":0, 
       "phoneNumber":0 
       }, 
      "office": 
       {"address":0, 
       "phoneNumber":0 
       } 
      }, 
    }, 

    "msg":"People data" 
} ; 

想這是我的JSON對象。 我想運行一個循環,並通過迭代值..

alert("json length = " + Object.keys(json).length); //2 
alert("keys in json : " + Object.keys(json)); //person,msg 

var people = json.person; 
var personLen = Object.keys(people).length; //3 

現在我想運行一個循環,進去P1,P2,P3 ..

for(i=0; i<people; i++) { 

    var person = people[i]; //but this doesnt work 

} 

值我如何使用循環獲取這些值?

回答

2

這會打印「undefined」的長度。

因爲它沒有屬性命名length,它不是這將有一個數組內置的財產length

如果你想在這個對象屬性的數量,然後嘗試

Object.keys(jsonObj).length 
+0

但是,如果我們把它通過ajax調用,我們可以使用長度。這是爲什麼? – Anjana

+0

你可以分享作爲AJAX響應得到的輸出嗎? – gurvinder372

+0

請檢查我的問題編輯.. – Anjana

1

上有對象沒有length屬性

var jsonObj = { 
    "firstname": "test", 
    "lastName": "test", 
    "email": "test", 
    "mobile": "test", 
    "place": "test", 
    "country": "test" 
}; 
// It will return an array of 6 elements['test','test','test','test','test','test'] 
var a =Object.keys(jsonObj) 
alert(a.length); 

JSFIDDLE