2013-04-13 62 views
0

我在StackOverflow上發現了很多線程,討論解析json數組,但我似乎無法弄清楚如何找回某些數據。以下是我有...在JavaScript中解析json數組與未知的字段名稱

$('#keyword_form').submit(function(e){ 
     var gj = $.post('employee_search.php',$('#keyword_form').serialize(),function(data){     
      if(!data || data.status !=1) 
      { 
       alert(data.message); 
       return false; 
      } 
      else 
      { 
       alert(data.message); 
      } 
     },'json'); 
     e.preventDefault(); 

    }); 

JSON數據發送給它看起來像這樣...

{ 
    "status":1, 
    "message":"Query executed in 9.946837 seconds.", 
    "usernames_count":{ 
     "gjrowe":5, 
     "alisonrowe":4, 
     "bob":"1" 
    } 
} 

正如我的功能顯示我可以做alert(data.message);,但我怎麼能訪問usernames_count數據?

我的疑惑來自數據沒有名稱/標籤的事實。 bob是一個用戶名和1是與該用戶名

相關聯。如果我做alert(usernames_count);我回來[object Object]

如果我做alert(usernames_count[0]);我回來了返回的計數undefined

我相信我應該做的事與JSON.parse();,但我還沒有得到它的權利尚未

+0

您是否有可能更改返回的數據? 'usernames_count'應該是一個數字,一個新的'users'字段應該是一個擁有用戶的數組。你不覺得嗎? –

+0

可能會讓您感到困惑的一件事是,usernames_count不是數組,它是一個JSON對象。 – elevine

+0

這是一個JavaScript對象,因此您可以使用'for ... in'或'Object.keys'來遍歷這些鍵。在ES6中,你也可以「爲... ...」。 – ZER0

回答

4

試試這個:

$.each(data.usernames_count, function(username, val) { 
    alert(username+" has a value of "+val); 
}); 
+0

是......那個竅門 - 100% –

4

可以使用Object.keysfor…in循環 - 還記得在這種情況下使用hasOwnProperty

var users = data.usernames_count; 
Object.keys(users).forEach(function(user) { 
    console.log(user, users[user]); 
}); 
+0

請記住,這在所有舊版瀏覽器中都不受支持。有關於如何添加向後功能的指南[這裏](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys)。 –

+0

@HannesJohansson如果舊版瀏覽器不支持它,我是否更安全地使用其他使用jQuery的答案? –

+0

如果你依靠jQuery沒有問題,當然。而且看起來你使用的是jQuery,所以我會選擇這個解決方案。如果你想要的代碼不依賴於jQuery,你可以像在Mozilla指南中那樣修補Object。 –

0

這聽起來像你的問題是如何通過在usernames_count對象的條目進行迭代。您可以這樣做:

var key = ''; 
for(key in data.usernames_count) { 

    //check that this key isn't added from the prototype 
    if(data.usernames_count.hasOwnProperty(key) { 
     var value = data.usernames_count[key]; 

     //do something with the key and value 
    } 
}