View a simple jQuery example to iterate 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); });
The above code snippet works fine, prompting “apple”, “orange”…etc., as expected.
Problem: JSON string
The following example declares a JSON string (enclosed in 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 the following error in the 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, convert it to a JavaScript object via 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); });