jquery each报 Uncaught TypeError: Cannot use 'in' operator to search for错误

在写前端的时候用jquery来遍历后台传来的json数组时候遇到这个错误:Uncaught TypeError: Cannot use 'in' operator to search for。后来查到原因是因为:一部分浏览器后端传过来的是json对象,但是我们前端是需要Javascript的对象,所以需要做个转换JSON.parse() or jQuery $.parseJSON



Review a simple jQuery example to loop over a JavaScript array object.

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);
});

Above code snippet is working fine, prompts the “apple”, “orange” … as expected.

Problem : JSON string

Review below example, declares a JSON string (enclosed with single or double quotes) directly.

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);
});

In Chrome, it shows following errors in console :

Uncaught TypeError: Cannot use 'in' operator to search for '156' 
in [{"id":"1","tagName":"apple"}...

Solution : Convert JSON string to JavaScript object

To fix it, converts it to Javascript object via standard JSON.parse() or jQuery $.parseJSON.

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);
});
Note
Most web applications will return JSON formatted string directly, you need to convert it to JavaScript object before parse it with jQuery.
参考链接:http://www.mkyong.com/jquery/jquery-loop-over-json-string-each-example/
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值