I'm quite new here and I am working with javascript and data manipulation using Datatables.
My api returs json data like this:
[
{
"id": 1,
"name": "qwert",
"lastname": "qwert",
"school": "qwert",
"parents": "qwert",
"About": "qqwewqeqwewqe"
},
{
"id": 2,
"name": "qwert",
"lastname": "qweere",
"school": "sadsadasd",
"parents": "asdasdasd",
"About": "asdasdasdasdasdasdas"
}
]
I have tried the following JS code with Datatables but doesn't seem to work:
$(document).ready(function () {
$('#tableofrequirement').DataTable({
ajax: 'example2.json',
"columns":[
{data: 'id'},
{data: 'name'},
{data: 'lastname'},
{data: 'school'},
{data: 'parents'},
{data: 'About'},
]
});
});
I have noticed, however, that if I download the json data and I manually change the format to the below the function works perfectly:
{
"data ":[
{
"id": 1,
"name": "qwert",
"lastname": "qwert",
"school": "qwert",
"parents": "qwert",
"About": "qqwewqeqwewqe"
},
{
"id": 2,
"name": "qwert",
"lastname": "qweere",
"school": "sadsadasd",
"parents": "asdasdasd",
"About": "asdasdasdasdasdasdas"
}
]
}
Is there any way I can tell Datatables the structure of my json or is there anyway I can easily reformat this on javascript?
Thanks in advance
CodePudding user response:
The returned json from you api is not valid, you are missing quotatin marks around this value "lastname": qwert,
I added an example with correct json data and it works just fine.
let data = [
{
"id": 1,
"name": "qwert",
"lastname": "qwert",
"school": "qwert",
"parents": "qwert",
"About": "qqwewqeqwewqe"
},
{
"id": 2,
"name": "qwert",
"lastname": "qweere",
"school": "sadsadasd",
"parents": "asdasdasd",
"About": "asdasdasdasdasdasdas"
}
];
$(document).ready(function () {
$('#table_id').DataTable({
data: data,
columns:[
{data: 'id'},
{data: 'name'},
{data: 'lastname'},
{data: 'school'},
{data: 'parents'},
{data: 'About'},
]
});
});
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw upLPUjgMXY0G 8O0xUf /Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.js"></script>
<table id="table_id" >
</table>