$.each遍历json对象

查看一个简单的jQuery的例子来遍历一个JavaScript数组对象。

  1. var json = [
  2.     {"id":"1","tagName":"apple"},
  3.     {"id":"2","tagName":"orange"},
  4.     {"id":"3","tagName":"banana"},
  5.     {"id":"4","tagName":"watermelon"},
  6.     {"id":"5","tagName":"pineapple"}
  7. ];
  8.    
  9. $.each(json, function(idx, obj) {
  10.     alert(obj.tagName);
  11. });

上面的代码片断工作正常,提示 "apple", "orange" … 等,如预期一样。

问题: JSON 字符串

下面的例子中,声明了一个JSON字符串(随附单或双引号)直接地。

  1. var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
  2. {"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
  3. {"id":"5","tagName":"pineapple"}]';
  4. $.each(json, function(idx, obj) {
  5.     alert(obj.tagName);
  6. });

在Chrome中,它显示在控制台下面的错误:

Uncaught TypeError: Cannot use 'in' operator to search for '156' 

in [{"id":"1","tagName":"apple"}...
			

            

解决方案:JSON字符串转换为JavaScript对象。
要修复它,通过标准JSON.parse()或jQuery 的 $.parseJSON 将其转换为JavaScript对象。

  1. var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
  2. {"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
  3. {"id":"5","tagName":"pineapple"}]';
  4. $.each(JSON.parse(json), function(idx, obj) {
  5.     alert(obj.tagName);
  6. });
  7. //or
  8. $.each($.parseJSON(json), function(idx, obj) {
  9.     alert(obj.tagName);
  10. });
posted @ 2017-06-25 15:16  李慕白520  阅读(135)  评论(0编辑  收藏  举报