【问题标题】:how to get to this JSON structure? in pure JS or JQuery如何得到这个 JSON 结构?在纯 JS 或 JQuery 中
【发布时间】:2016-01-23 14:08:28
【问题描述】:

在 json 响应的下面部分,我如何获取 rows 对象中的对象,我需要对所有 id 和其他属性进行循环。 ,它不是一个数组,所以 active_chats.rows[1].id 不起作用。提前感谢您的回答

 {
"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

【问题讨论】:

标签: javascript jquery json object


【解决方案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(打印到控制台)

应该做的伎俩

【讨论】:

  • 谢谢,这就是我所需要的
【解决方案2】:

为了访问你必须做的 id:

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

这里的 obj 是您保存 JSON 的任何变量。遍历 active_chats 和行的长度将帮助您逐步完成每个值。

此外,您可以将您的 JSON 扔到此站点上的文本框中,以更好地了解正在发生的事情:http://jsbeautifier.org

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    相关资源
    最近更新 更多