2016-01-23 26 views
-2

下面是json響應的一部分,我如何得到行對象中的對象,我需要爲所有的id和其他屬性做循環。 ,它不是一個數組,因此active_chats.rows [1] .id不起作用。在此先感謝答案如何獲得這個JSON結構?在純JS或JQuery中

{ 
"active_chats":{ 
"rows":{ 
"2":{ 
"id":"2", 
"nick":"bart", 
"status":"1", 
"time":"1453463784", 
"user_id":"2", 
"hash":"183c12afef48ea9942e5c0a7a263ef441039d832", 
"ip":"::1", 
"dep_id":"2", 
"support_informed":"1", 
"has_unread_messages":"1", 
"last_user_msg_time":"1453476440", 
"last_msg_id":"11", 
"wait_time":"5171", 
"user_tz_identifier":"Europe/Paris", 
"nc_cb_executed":"1", 
"user_closed_ts":"1453470674", 
"department_name":"ECODEMO" 
}, 
"3":{ 
"id":"3", 
"nick":"robert", 
"status":"1", 
"time":"1453470058", 
"user_id":"2", 
"hash":"0fae69094667e452b5401552541602d5c2bd73ef", 
"ip":"127.0.0.1", 
"dep_id":"2", 
"user_status":"1", 
"support_informed":"1", 
"user_typing":"1453479978", 
"user_typing_txt":"Gość opuścił chat!", 
"last_msg_id":"10", 
"wait_time":"3285", 
"user_tz_identifier":"Europe/Paris", 
"nc_cb_executed":"1", 
"user_closed_ts":"1453479983", 
"unanswered_chat":"1", 
"department_name":"ECODEMO" 
} 
}, 
"size":2 
+1

好像是JSON格式了。雖然無效。 – Daenarys

+0

[如何遍歷JavaScript對象的屬性名稱?](http://stackoverflow.com/questions/1876485/how-to-iterate-through-property-names-of-javascript-object) – nothingisnecessary

回答

1

只是做

for (var key in p) { 
    if (p.hasOwnProperty(key)) { 
    console.info(key + " => " + p[key]); 
    } 
} 

其中p爲您的JSON響應對象

在這裏做一些測試,您的JSON是無效的..但如果固定:

for(var row in response.active_chats.rows) 
    { 
    for (var key in response.active_chats.rows[row]) { 
     console.log(key + " => " + response.active_chats.rows[row][key]); 
    } 
} 

fiddle example(打印到控制檯)

應該做的伎倆

+0

謝謝,這就是我需要的所有 –

+0

沒有概率,很樂意提供幫助 – rmjoia

0

爲了訪問ID,你必須做的:

var number = 2 
var idVal = obj.active_chats.rows[number].id; // idVal = 2 

這裏的obj是任何變量,您在保存的JSON通過active_chats和行會的長度循環。然後幫助你逐步瞭解每個值。

此外,您還可以折騰你的JSON文本框在這個網站得到什麼是怎麼回事更好的畫面:http://jsbeautifier.org

相關問題