2013-12-20 65 views
-1

我正在Django框架上開發一個網站,它返回一個使用jQuery數據表的json響應。 Datatable需要輸入爲javascript對象或arrys數組,所以我需要將其在服務器端或客戶端轉換爲javascript對象或數組。Json to Javascript對象或數組

這是數據表的相關文檔。

DataTables AJAX source example DataTables AJAX source example - array of objects as a data source

[ 
    { 
     "pk": 7, 
     "model": "softwareapp.software", 
     "fields": { 
      "city": "miami", 
      "submitted_by": [], 
      "description": "test", 
      "title": "test", 
      "zipcode": "test", 
      "rating_votes": 0, 
      "state": "fl", 
      "address": "test", 
      "rating_score": 0, 
      "business_size": [ 
       5 
      ], 
      "slug": "test", 
      "developer": "test" 
     } 
    }, 
    { 
     "pk": 8, 
     "model": "softwareapp.software", 
     "fields": { 
      "city": "", 
      "submitted_by": [], 
      "description": "", 
      "title": "test2", 
      "zipcode": "", 
      "rating_votes": 0, 
      "state": "", 
      "address": "", 
      "rating_score": 0, 
      "business_size": [ 
       5 
      ], 
      "slug": "test2", 
      "developer": "" 
     } 
    }, 
    { 
     "pk": 10, 
     "model": "softwareapp.software", 
     "fields": { 
      "city": "", 
      "submitted_by": [], 
      "description": "", 
      "title": "test3", 
      "zipcode": "", 
      "rating_votes": 0, 
      "state": "", 
      "address": "", 
      "rating_score": 0, 
      "business_size": [ 
       6 
      ], 
      "slug": "test3", 
      "developer": "" 
     } 
    } 
] 
+0

谷歌「Json to Javascript對象」點擊第一個鏈接。 – Blender

回答

0

大多數瀏覽器支持JSON.parse(),這是在ECMA-262第5版(即JS是基於本說明書中)所定義。它的用法很簡單:

var json = '{"result":true,"count":1}', 
obj = JSON.parse(json); 

alert(obj.count); 

對於那些不能使用json2.js來實現的瀏覽器。

0

在客戶端,你可以使用:

JSON.parse(json) 

「JSON」 是JSON字符串。

或者,如果您還使用jQuery來執行AJAX請求,它將在「成功」處理程序中爲您執行反序列化。

 $.ajax({ 
     type: "GET", 
     url: "your url", 
     dataType: "json", 
     contentType: "application/json", 
     success: function (e) { 
      // the value of "e" should be a javascript object or array depending on the response 

     } 
    });