Display nested JSON data in jquery datatables

后端 未结 1 1613
故里飘歌
故里飘歌 2021-01-15 08:28

After making a POST request using AJAX I get the following JSON response:

    {
\"ServiceName\": \"ABC\",
\"Response\": {
    \"Object\": [
        {
                


        
相关标签:
1条回答
  • 2021-01-15 09:06

    You must iterate over the response and convert it into a format dataTables can comprehend. As I read the sample data you have an Object holding blocks of Attributes holding an Attribute with key => value pairs as AttributeName => AttributeValue. So parse the response in a dataSrc callback :

    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' }
        ]    
    })
    

    the dataSrc callback return an array of objects on the form :

    data = [
      { Code: "576", Country: "Americas", Name: "XYZ", Place: "Abc" },
      { Code: "536", Country: "India", Name: "XYZHJ", Place: "Abchgh" }
    ]
    
    0 讨论(0)
提交回复
热议问题