Ali Alhamaly Ali Alhamaly - 1 year ago 68
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
and then serialize this list using
object, and this object returns the following

"status_message":"Lights still flashing",
"crm_services_id":"1", "subject_id":"Lights are flashing",
"status_message":"lights working fine",
"subject_id":"Lights are flashing",

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
response that is acceptable to a
which is as follow:

"data": [
"Tiger Nixon",
"System Architect",
"Garrett Winters",

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

Answer Source

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])){
    return columnsArray;
$(document).ready(function() {
  var table = $('#example').DataTable({
    "columns": getColumns(),
    "data": data

Working example. Hope that helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download