ASP.NET+jQuery, how to deSerialize JSON?

后端 未结 2 526
滥情空心
滥情空心 2020-12-17 06:11

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

相关标签:
2条回答
  • 2020-12-17 06:29

    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.

    0 讨论(0)
  • 2020-12-17 06:46

    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>
    
    0 讨论(0)
提交回复
热议问题