$. Each traverses the json object, and the. each calendar 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 );
});
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 '156' 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 );
});