我正在开发一个关于Django框架的网站,它返回一个json响应,用于使用jquery数据表。数据表需要输入为javascript对象或arrys数组,所以我需要在服务器端或客户端将其转换为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 :(得分:0)
大多数浏览器都支持JSON.parse(),这是在ECMA-262第5版(JS所基于的规范)中定义的。它的用法很简单:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
对于没有的浏览器,您可以使用json2.js实现它。
答案 1 :(得分:0)
在客户端上,您可以使用:
JSON.parse(json)
“json”是JSON字符串。
或者,如果您还使用jQuery来执行AJAX请求,它将在“success”处理程序中为您执行反序列化。
$.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
}
});