2013-09-27 77 views
-2

我有以下JSON代碼:JSON的foreach不工作

{ 
    "chat": [ 
     { 
      "username": "demo", 
      "text": "hi man", 
      "time": "1380167419" 
     }, 
     { 
      "username": "admin", 
      "text": "hi", 
      "time": "1380167435" 
     }, 
     { 
      "username": "demo", 
      "text": "this works flawless now.", 
      "time": "1380167436" 
     }, 
     { 
      "username": "demo", 
      "text": "we basically done/", 
      "time": "1380167443" 
     } 
    ] 
} 

當我運行:

var codes = JSON.parse(history); //history is the above JSON. 
$.each(codes, function(key, value){ 
alert(value.chat.username); 
}); 

它沒有任何警告,並不斷告訴我value.chat.username是不確定的...

我在哪裏做錯了?

+1

你不明白爲什麼那些倒票...但感謝你的幫助球員。 – jackhao

回答

1

這個時候你必須在value.chat定義對象的數組。在查看username之前,您需要選擇一個數組元素。正確的格式是value.chat[n].username,其中n是數組中的索引。如果你想通過數組中的chat對象上進行迭代,你需要這樣做:

$.each(codes.chat, function(key, value){ 
    alert(value.username); 
}); 

注意,我們現在遍歷chat,所以我們可以在每個chat元素直接處理性能。

+0

非常感謝。 – jackhao

2

您不需要解析JSON。它已經是JSON對象

$.each(history.chat, function(key, value){ 
alert(value.username); 
}); 

您還必須迭代聊天數組並正確引用其項目。

0

那是......因爲.chat沒有定義

var codes = JSON.parse(history); //history is the above JSON. 
$.each(codes.chat, function(key, value){ 
    alert(value.username); 
});