【问题标题】:json foreach array of arrays with jqueryjson foreach 带有 jquery 的数组数组
【发布时间】:2023-03-11 07:20:01
【问题描述】:
[
    [
        {
            "Id": 3,
            "Code": "232",
            "TicketImage": "0"
        }
    ],
    [
        {
            "Id": 1,
            "Code": "23",
            "TicketImage": "1"
        },
        {
            "Id": 2,
            "Code": "24",
            "TicketImage": "1"
        }
    ],
    []
]

我有这个我试图解析的 JSon 对象。

var res = jQuery.parseJSON(JSON.stringify(obj.Message));

              $.each(res, function (i, tickets) {
                  $.each(tickets, function (i, ticket) {
                      console.log($(this));
                  });
              });

当我尝试这个时,我会收到无数带有字母的弹出窗口。但我想要对象。

如何解析这个 JSON 数据?

更新:

           $.each(res, function (i, tickets) {
                  $.each(tickets, function (i, ticket) { 
                      console.log(ticket.Code);
                      console.log(ticket.TicketImage);
                  });
              });

做到了。

【问题讨论】:

  • $(this) 会给你对象吗? .each 循环内> 除非我遗漏了其他东西:) 希望这会有所帮助
  • obj.Message 有 JSON 数据。
  • console.log(obj.message) 以确保数据正确。然后 console.log(res) 以确保它解析正确。
  • @MatthewBlancarte 是的,它们被正确解析了。
  • @Tats_innit 仍然有无数的警报,全部未定义。

标签: javascript jquery json foreach


【解决方案1】:

试试:

var res = jQuery.parseJSON(eval(obj.Message));

【讨论】:

  • 如果obj.Message 是一个有效的JSON 字符串,那么绝对不需要使用evil
【解决方案2】:

小心你覆盖了 i 变量:

$.each(res, function (i, tickets) {
                  $.each(tickets, function (j, ticket) {
                      console.log(this);
                      // as a full string
                      console.log(this.ticketId+' : '+JSON.stringify(this));

                  });
});

​除了这个小东西,你的循环是正确的,你不需要你的'this'上的jquery包装器。在 $.each(array,function(k,v){}) 中,k 变量是检索当前对象的键,v 是它的值,因此您也可以通过这样做来访问它:

$.each(res, function (i, tickets) {
                  $.each(res[i], function (j, ticket) {
                      console.log(res[i][j].ticketId+' : '+res[i][j]);
                      // which is the exact same thing as :
                      console.log.(ticket);
                      // and even this:
                      console.(this);

                  });
});

使用'this'的相同代码:

$.each(res, function (i, tickets) {
                  $.each(this, function (j, ticket) {
                      console.log(this.ticketId+' : '+this);
                  });
});

使用每个值:

$.each(res, function (i, tickets) {
                  $.each(tickets, function (j, ticket) {
                      console.log(ticket.ticketId+' : '+ticket);
                  });
});

【讨论】:

    猜你喜欢
    • 2010-10-19
    • 1970-01-01
    • 2019-12-08
    • 1970-01-01
    • 2013-01-25
    • 2011-03-03
    • 2018-05-10
    • 2012-12-26
    • 1970-01-01
    相关资源
    最近更新 更多