小编典典

在jQuery数据表中显示嵌套的JSON数据

ajax

使用AJAX发出POST请求后,我得到以下JSON响应:

    {
"ServiceName": "ABC",
"Response": {
    "Object": [
        {
            "Attributes": {
                "Attribute": [
                    {
                        "AttributeName": "Name",
                        "AttributeValue": "XYZ"
                    },
                    {
                        "AttributeName": "Place",
                        "AttributeValue": "Abc"
                    },
                    {
                        "AttributeName": "Country",
                        "AttributeValue": "Americas"
                    },
                    {
                        "AttributeName": "Code",
                        "AttributeValue": "576"
                    }
                ]
            }
        },
        {
            "Attributes": {
                "Attribute": [
                    {
                        "AttributeName": "Name",
                        "AttributeValue": "XYZHJ"
                    },
                    {
                        "AttributeName": "Place",
                        "AttributeValue": "Abchgh"
                    },
                    {
                        "AttributeName": "Country",
                        "AttributeValue": "India"
                    },
                    {
                        "AttributeName": "Code",
                        "AttributeValue": "536"
                    }
                ]
            }
        }
    ]
}}

我正在使用数据表来显示数据..但是使用此嵌套的JSON,我无法直接获取数据。我正在使用此https://datatables.net/examples/server_side/post.html

https://datatables.net/reference/option/ajax.dataSrc作为参考。


阅读 220

收藏
2020-07-26

共1个答案

小编典典

您必须遍历响应并将其转换为dataTables可以理解的格式。当我读取样本数据时,您拥有一个包含with键=>值对as =>
Object保存块。因此,在回调中解析响应:Attributes``Attribute``AttributeName``AttributeValue``dataSrc

var table = $("#example").DataTable({
    ajax : {
        url : 'nestedData.json',
        dataSrc : function(json) {
            var temp, item, data = [];
            for (var i=0;i<json.Response.Object.length;i++) {
                temp = json.Response.Object[i].Attributes.Attribute;
                item = {};
                for (var elem in temp) {            
                    item[temp[elem].AttributeName] = temp[elem].AttributeValue
                }
                data.push(item);
            }
            return data
        }
    },
    columns : [
        { data : 'Name', title : 'Name' },
        { data : 'Place', title : 'Place'  },
        { data : 'Country', title : 'Country' },        
        { data : 'Code', title : 'Code' }
    ]    
})

所述dataSrc回调返回窗体上对象的数组:

data = [
  { Code: "576", Country: "Americas", Name: "XYZ", Place: "Abc" },
  { Code: "536", Country: "India", Name: "XYZHJ", Place: "Abchgh" }
]
2020-07-26