【问题标题】:Json to Javascript object or Array [duplicate]Json 到 Javascript 对象或数组 [重复]
【发布时间】:2014-01-09 16:15:18
【问题描述】:

我正在 Django 框架上开发一个站点,它返回一个 json 响应以用于 jquery 数据表。 Datatable 要求输入是 javascript 对象或数组,因此我需要在服务器端或客户端将其转换为 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": ""
        }
    }
]

【问题讨论】:

  • Google "Json to Javascript object" 点击第一个链接。

标签: javascript django json jquery-datatables


【解决方案1】:

在您可以使用的客户端上:

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

        }
    });

【讨论】:

    【解决方案2】:

    大部分浏览器都支持JSON.parse(),这是在ECMA-262 5th Edition(JS 所基于的规范)中定义的。它的用法很简单:

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

    对于不支持的浏览器,您可以使用json2.js 实现它。

    【讨论】:

      猜你喜欢
      • 2016-08-26
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 2018-06-19
      • 2020-02-06
      • 2012-12-22
      • 2015-04-21
      • 1970-01-01
      相关资源
      最近更新 更多