首页 > 代码库 > JQuery $.each遍历JSON字符串报Uncaught TypeError:Cannot use 'in' operator to search for
JQuery $.each遍历JSON字符串报Uncaught TypeError:Cannot use 'in' operator to search for
查看一个简单的jQuery的例子来遍历一个JavaScript数组对象。
[js] view plaincopy
- var json = [
- {"id":"1","tagName":"apple"},
- {"id":"2","tagName":"orange"},
- {"id":"3","tagName":"banana"},
- {"id":"4","tagName":"watermelon"},
- {"id":"5","tagName":"pineapple"}
- ];
- $.each(json, function(idx, obj) {
- alert(obj.tagName);
- });
上面的代码片断工作正常,提示 “apple”, “orange” … 等,如预期一样。
问题: JSON 字符串
下面的例子中,声明了一个JSON字符串(随附单或双引号)直接地。
[js] view
plaincopy
- var json = ‘[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
- {"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
- {"id":"5","tagName":"pineapple"}]‘;
- $.each(json, function(idx, obj) {
- alert(obj.tagName);
- });
在Chrome中,它显示在控制台下面的错误:
Uncaught TypeError: Cannot use ‘in‘ operator to search for ‘156‘
in [{"id":"1","tagName":"apple"}...
解决方案:JSON字符串转换为JavaScript对象。
要修复它,通过标准JSON.parse()或jQuery 的 $.parseJSON 将其转换为JavaScript对象。
[js] view
plaincopy
- var json = ‘[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
- {"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
- {"id":"5","tagName":"pineapple"}]‘;
- $.each(JSON.parse(json), function(idx, obj) {
- alert(obj.tagName);
- });
- //or
- $.each($.parseJSON(json), function(idx, obj) {
- alert(obj.tagName);
- });
JQuery $.each遍历JSON字符串报Uncaught TypeError:Cannot use 'in' operator to search for
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。