Ali Alhamaly Ali Alhamaly - 1 month ago 12
Ajax Question

Serialize list of dictionaries into accepted DataTable Ajax object

I have a web application in which I'm retrieving some data into bootstrap table, what i want to do now is to use

jQuery DataTable
instead of the current as it has too much useful features.

Currently I'm retrieving the data from the server side using OOP approach, where a class object represents a data row in a particular table, and this object includes a dictionary which stores column names and values.

What I'm doing now is that I'm retrieving these class objects and append each dictionary of each object in a
List<Item>
and then serialize this list using
JavaScriptSerializer
object, and this object returns the following
JSON
format:

[
{
"slno":"2",
"status_message":"Lights still flashing",
"crm_services_id":"1", "subject_id":"Lights are flashing",
"severity_id":"5",
"user_id":"husain.alhamali",
"status_id":"1"
},
{
"slno":"3",
"status_message":"lights working fine",
"crm_services_id":"2",
"subject_id":"Lights are flashing",
"severity_id":"3",
"user_id":"husain.alhamali",
"status_id":"2"
}
]


When i tried to use this object to fill my
DataTable AJAX
I've got an error says:


Invalid JSON response


I saw some examples of a valid
JSON
response that is acceptable to a
DataTable
which is as follow:

{
"data": [
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$320,800"
],
[
"Garrett Winters",
"Accountant",
"Tokyo",
"8422",
"2011/07/25",
"$170,750"
]
}


Now my question is is there any tool or plugin that could re-format my
JSON
string into an acceptable format like the one above?

Answer

With this HTML:

<table id="example"></table>

This JS will create a table:

var data = [{
  "slno": "2",
  "status_message": "Lights still flashing",
  "crm_services_id": "1",
  "subject_id": "Lights are flashing",
  "severity_id": "5",
  "user_id": "husain.alhamali",
  "status_id": "1"
}, {
  "slno": "3",
  "status_message": "lights working fine",
  "crm_services_id": "2",
  "subject_id": "Lights are flashing",
  "severity_id": "3",
  "user_id": "husain.alhamali",
  "status_id": "2"
}];

function getColumns(){
  for(var i = 0; i < data.length; i++){
    let columnsArray = [];
    var keys = Object.keys(data[i]);
    for(k in Object.keys(data[i])){
      if(data[i].hasOwnProperty(keys[k])){
        columnsArray.push({
            "data":keys[k]
        });
      }
    }
    return columnsArray;
  }
}
$(document).ready(function() {
  var table = $('#example').DataTable({
    "columns": getColumns(),
    "data": data
  });
});

Working example. Hope that helps.