I want to deserialize the JSON string below, using jQuery each function, but the item is undefined.
there is the code below, but, in case I am using asp.net 2.0 + we
Just use the built-in JavaScript eval method:
$.each(eval('(' + $strJson + ')'), function(key, item) {
Incidentally, you don't need to use the $ sign for variables in JavaScript.
Have you tried using ASP.NET's Sys.Serialization.JavaScriptSerializer's deserialize method?
var result = Sys.Serialization.JavaScriptSerializer.deserialize($strJson);
Alternatively, there is json_parse
var result = json_parse($strJson, [reviver])
This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted.
Working Example here. Here's the code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="http://www.json.org/json_parse.js"></script>
<script type="text/javascript">
$(function() {
var $strJson = '[';
$strJson += '{"Code":"a","Name":"Sam","Country":"US"},';
$strJson += '{"Code":"b","Name":"John","Country":"CN"},';
$strJson += '{"Code":"c","Name":"Mary","Country":"TW"}';
$strJson += ']';
var result = json_parse($strJson);
$.each(result, function(key, item) {
alert("Code: " + item.Code + " ,Name: " + item.Name + " ,Country: " + item.Country);
//Taken the following out as it prevents objects after the first from being "alerted"
//if ( key == 0) return false; //Prevent infinity loop
});
});
</script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
</head>
<body>
<p>Example Page</p>
</body>
</html>