jQuery: 遍历json字符串, 遍历object数组,报错:Uncaught TypeError: Cannot use ‘in’ operator to search for ‘156’, Uncaught SyntaxError: Unexpected token k in JSON at position 2, loop over JSON string – $.each example

 

jQuery: 遍历json字符串, 遍历object数组,报错:Uncaught TypeError: Cannot use 'in' operator to search for '156', Uncaught SyntaxError: Unexpected token k in JSON at position 2, loop over JSON string – $.each example
jQuery: 遍历json字符串, 遍历object数组,报错:Uncaught TypeError: Cannot use ‘in’ operator to search for ‘156’, Uncaught SyntaxError: Unexpected token k in JSON at position 2, loop over JSON string – $.each example

 

遍历一个json字符串,或者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

现在定义一个json字符串的话,我们再试试:

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

 

在console调试面板上,直接报错:

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

或者还有

Uncaught SyntaxError: Unexpected token k in JSON at position 2

 

解决方法 Solution :  转换 json字符串 为 JavaScript object, 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);
});

 

问题解决!

 

 PS:

json 字符串不要写成:

var json = '[{id:"1","tagName":"apple"},{id:"2","tagName":"orange"},
{id:"3","tagName":"banana"},{id:"4","tagName":"watermelon"},
{id:"5","tagName":"pineapple"}]';

 

键名 id 是需要用双引号包裹的!

 

本文:jQuery: 遍历json字符串, 遍历object数组,报错:Uncaught TypeError: Cannot use ‘in’ operator to search for ‘156’, Uncaught SyntaxError: Unexpected token k in JSON at position 2, loop over JSON string – $.each example

Leave a Reply