I would like to build a generic CSV viewer with DataTables.
"generic" means that it should be capable to read any CSV acquired externally and represent into a Jquery DataTables
I'm starting from a JSON structure (obtained after CSV parsing) and defining this table:
| Name | Surname | Age |
|---|---|---|
| Stefano | Rxxxx | 45 |
| Test | Dummy | 50 |
I would then like to show as Jquery DataTables (https://datatables.net/) but it's not clear why I cannot reach my goal:
$(function() {
data = [
{"Name":"Stefano","Surname":"Rxxxx","Age":"45"},
{"Name":"Test","Surname":"Dummy","Age":"50"}
]
columns = [];
$.each(data[0], function(k, v) {
$('#example > thead > tr').append("<td>" + k + "</td>");
columns.push(k);
});
console.log(columns);
$('#example').DataTable({
data: data,
columns: columns
});
});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css"/>
<script src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<table id='example' class='display'>
<thead><tr></tr></thead>
</table>
On consolle I have:
- a WARNING
jquery.min.js:2 jQuery.Deferred exception: Cannot use 'in' operator to search for 'length' in Name TypeError: Cannot use 'in' operator to search for 'length' in Name
- an ERROR
jquery.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in Name
...but it's not clear to me what's wrong or missing in my code to translate a JSON table into a JQUERY DataTables.
Any help is appreciated.
jquery.dataTables.min.js:126 Uncaught TypeError: Cannot read properties of undefined (reading 'asSorting')- this is because yourtheadneeds atr- add that (and change the corresponding .append and your table loads at least (though has no rows/data): jsfiddle.net/45f9ob37