0

REF: https://datatables.net/

Is it possible with data-tables to convert a single object json returned from server to rows of a table with key being column1 and value as column2.

Single Object Json from server:

{"data":"abc","name":"Diago","Age":23}

Sample Table: generated with above json with key:value pair as row

----------------------
| key    |    value  |
----------------------
| data   |   abc     |
| name   |   Diago   |
| Age    |   23      |

2 Answers 2

1

You will love this:

https://igniteui.com/grid/overview

Standard solution:

var json = {"data":"abc","name":"Diago","Age":23};
var output = [];
output.push("<table>");
$.each(json, function(k, v) {
            output.push("<tr><td>");
            output.push(k);
            output.push("</td><td>");
            output.push(v);    
            output.push("</td></tr>");
});
output.push("</table>");

console.log(output.join(""));

DEMO

FULL SOLUTION TO YOUR QUESTION:

jQuery:

$(document).ready( function () {

  var json = {"data":"abc","name":"Diago","Age":23};
  var output = [];
  output.push("<table>");
  $.each(json, function(k, v) {
            output.push("<tr><td>");
            output.push(k);
            output.push("</td><td>");
            output.push(v);    
            output.push("</td></tr>");
  });
  output.push("</table>");

  $("#container").append(output.join(""));

  $("#container").find("table").dataTable();


});

HTML:

<!DOCTYPE html>
<html>
    <head>
        <link href="//datatables.net/download/build/nightly/jquery.dataTables.css" rel="stylesheet" type="text/css" />

        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script src="//datatables.net/download/build/nightly/jquery.dataTables.js"></script>

        <meta charset=utf-8 />
        <title>DataTables - JS Bin</title>
    </head>
    <body>
        <div id="container">
        </div>
    </body>
</html>
Sign up to request clarification or add additional context in comments.

2 Comments

Yes I get what you are suggesting but I need native datatables solution like aoColumn options et. when provided ajax url.
so put those settings in .dataTable()
0

Got it working with this code:

$(function() {
  json = '[{"data":"abc","name":"Diago","Age":23}]';

  parsedJson = JSON.parse(json);
  var otable = $("#datatable").dataTable();
  otable.fnClearTable();
  $.each(parsedJson[0], function(key, value) {
    otable.dataTable().fnAddData([
      key,
      value
    ]);
  })
});

Example here

Hope this helps

1 Comment

I did similar as i found I cant do it inside Otable as we do manipulate columns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.