JQuery $. each traverses the JavaScript array object instance, jquery. each
View a simple jQuery example to traverse 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);});
The code snippet above works normally and prompts "apple", "orange "... As expected.
Question: JSON string
In the following example, a json string (with a single or double quotation mark) is declared 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 displays errors in the console:
Uncaught TypeError: Cannot use 'in' operator to search for '000000'
In [{"id": "1", "tagName": "apple "}...
Solution: convert a JSON string to a JavaScript Object.
To fix it, convert it to a JavaScript Object through standard JSON. parse () or jQuery's $. 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);});
Reference: http://www.codes51.com/article/detail_641.html