Look at a simple jquery example to traverse a JavaScript array object.
varJSON = [ {"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 fine, prompting "Apple", "orange" ... And so on, as expected.
Problem: JSON string
In the following example, a JSON string (enclosed in single or double quotation marks) is declared directly.
varJSON ='[{"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 error under the console:
Uncaught typeerror:cannot use ' on ' operator to search for ' 156 ' in [{' id ': ' 1 ', ' tagName ': ' Apple '} ...
Solution: The JSON string is converted to a JavaScript object.
To fix it, convert it to a JavaScript object by using standard Json.parse () or jquery's $.parsejson.
varJSON ='[{"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);});
$.each traversing JSON objects