2012-11-19 33 views
1

这里是我的JSON对象:jQuery的每个分割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:“”“} localhost:317 字符串{0:”1“} localhost:317 字符串{0: “” “} 本地主机:317 字符串{0:”, “} 本地主机:317 字符串{0: ”“”} 本地主机:317 字符串{0: “i” 的}

我在做什么错?如何遍历对象?

回答

2

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

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

TL; DR

更改此:

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

要:

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

谢谢...我认为这就是它! – hjuster

0

这是因为家是一个字符串。我asssume你打算使用对象文本语法(例如,作为一个数组)声明它:

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\"}];