1. 程式人生 > >JSON.parse()方法

JSON.parse()方法

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <title>JSON.parse()</title>  
  5. <script type="text/javascript" src="json2.js"></script>  
  6. <script type="text/javascript">  
  7.     var data='{'  
  8.     +'"root":'  
  9.     +'['  
  10.     +'{"name":"1","value":"0"},'  
  11.     +'{"name":"6101","value":"西安市"},'   
  12.     +'{"name":"6102","value":"銅川市"},'   
  13.     +'{"name":"6103","value":"寶雞市"},'  
  14.     +'{"name":"6104","value":"咸陽市"},'   
  15.     +'{"name":"6105","value":"渭南市"},'  
  16.     +'{"name":"6106","value":"延安市"},'   
  17.     +'{"name":"6107","value":"漢中市"},'   
  18.     +'{"name":"6108","value":"榆林市"},'   
  19.     +'{"name":"6109","value":"安康市"},'   
  20.     +'{"name":"6110","value":"商洛市"}'   
  21.     +']'  
  22.     +'}';   
  23.     //示例1:此示例使用 JSON.parse 將 JSON 字串轉換為物件  
  24.     var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';  
  25.     var contact = JSON.parse(jsontext);  
  26.     document.write(contact.surname + ", " + contact.firstname + ", "+ contact.phone);  
  27.     //dateReviver  
  28.     //var dateObj = new Date(Date.UTC('2008', +'01' - 1, +'01', +'12', +'00', +'00'))  
  29.     //alert(dateObj.toUTCString())  
  30.     //示例2:此示例使用 JSON.parse 反序列化 ISO 格式的日期字串, 將返回Date格式物件。  
  31.     var jsontext2 = '{ "hiredate": "2008-01-01T12:00:00Z", "birthdate": "2008-12-25T12:00:00Z" }';  
  32.     var dates = JSON.parse(jsontext2, dateReviver);  
  33.     document.write("<br /><br />"+dates.birthdate.toUTCString());  
  34.     function dateReviver(key, value) {  
  35.         var a;  
  36.         if (typeof value === 'string') {  
  37.             a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);  
  38.             if (a) {  
  39.                 return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],  
  40.                                 +a[5], +a[6]));  
  41.             }  
  42.         }  
  43.         return value;  
  44.     };  
  45. </script>  
  46. </head>  
  47. <body>  
  48. </body>  
  49. </html>