【问题标题】:jquery each splitting json to single charactersjquery每个将json拆分为单个字符
【发布时间】:2012-11-07 11:40:57
【问题描述】:

这是我的 json 对象:

var home = "[{\"id\":\"1\",\"img\":\"assets\\\/1.jpg\",\"headline\":\"This is the headline in the pedu.\",\"text\":\"To the ipedu\"},{\"id\":\"2\",\"img\":\"assets\\\/2.jpg\",\"headline\":\"This is the headline in the pedulence.\",\"text\":\"To the pendula\"}]";

当我尝试像这样遍历对象时:

$.each(home, function() {
    console.log(this);
});

我记录了每个字符而不是整个字符串。

示例: 字符串 {0: "["} 本地主机:317 字符串 {0: "{"} 本地主机:317 字符串 {0: """} 本地主机:317 字符串 {0: "i"} 本地主机:317 字符串 {0: "d"} 本地主机:317 字符串 {0: """} 本地主机:317 字符串 {0: ":"} 本地主机:317 字符串 {0: """} 本地主机:317 字符串 {0: "1"} 本地主机:317 字符串 {0: """} 本地主机:317 字符串 {0: ","} 本地主机:317 字符串 {0: """} 本地主机:317 字符串 {0: "i"}

我做错了什么?如何循环遍历对象?

【问题讨论】:

    标签: php jquery json each


    【解决方案1】:

    这是因为 home 是一个字符串。我假设您打算使用对象文字语法(例如作为数组)声明它:

    var home = [{\"id\":\"1\",\"img\":\"assets\\\/1.jpg\",\"headline\":\"This is the headline in the pedu.\",\"text\":\"To the ipedu\"},{\"id\":\"2\",\"img\":\"assets\\\/2.jpg\",\"headline\":\"This is the headline in the pedulence.\",\"text\":\"To the pendula\"}];
    

    【讨论】:

      【解决方案2】:

      首先,你拥有的不是 JSON 对象;它是一个包含符合 JSON 规范的对象表示的字符串。

      要将该字符串转换为预期的对象,您必须首先使用$.parseJSON() 对其进行解析。

      TL;DR

      改变这个:

      $.each(home, function() {
          console.log(this);
      });
      

      收件人:

      $.each($.parseJSON(home), function() {
          console.log(this);
      });
      

      【讨论】:

      • 谢谢...我想就是这样!
      猜你喜欢
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      相关资源
      最近更新 更多