Can Jquery Data table read differntly formatted json? - javascript

I am using jQuery dataTables for grids (http://www.datatables.net/).
However my json is formatted differently than the json example included with dataTables docs. Is it possible for dataTables to interpret the formatting in our json?
Their json looks like this
{"aaData": [
[
"Trident",
"Internet Explorer 4.0",
"Win 95+",
"4",
"X"
],
[
"Trident",
"Internet Explorer 5.0",
"Win 95+",
"5",
"C"
]
]
}
My JSON looks like this and unfortunately I can't change it to look like the example included in their docs.
"allconfig": {
"card.inserted": {
"value": "Not Inserted",
"type": "enum",
"range": "",
"clone": false,
"archive": false,
"access": "R"
},
"card.cisproc": {
"value": "Processed",
"type": "string",
"range": "",
"clone": false,
"archive": false,
"access": "R"
}
}
}
Here is my jQuery
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"sAjaxSource": 'json/test.json'
});
});

You can change your json format to required format.
Use
$.getJSON('json/test.json', function(data) {
var newJson = [];
var myJson = data ;
$.each(myJson.allconfig, function (key, value) {
var rowArray = [];
rowArray.push(key);
$.each(myJson.allconfig[key], function (key1, value1) {
rowArray.push(value1);
});
newJson.push(rowArray);
});
$('#example').dataTable( { "bProcessing": true, "aaData":newJson });
});
check http://jsfiddle.net/JASdL/

Related

Reading arrays within arrays of a json file

I am building a site which will output data from a JSON file into a table, but I am having issues getting the content to output. This JSON file is generated from another site which surfaces documentation, while my site just creates a table for easy searching of those docs.
SAMPLE JSON for 2 docs:
[{
"title": "SampleTitleA",
"lang": "en-US",
"lastEdition": "2020-07-28",
"version": "1.0",
"metadata": [
{
"key": "sampleKeyA1",
"label": "sampleLabelA1",
"values": ["sampleValueA1"]
},
{
"key": "sampleKeyA2",
"label": "sampleLabelA2",
"values": ["sampleValueA2"]
}]
},
{
"title": "SampleTitleB",
"lang": "en-US",
"lastEdition": "2020-07-28",
"version": "1.0",
"metadata": [
{
"key": "sampleKeyB1",
"label": "sampleLabelB1",
"values": ["sampleValueB1"]
},
{
"key": "sampleKeyB2",
"label": "sampleLabelB2",
"values": ["sampleValueB2"]
}]
}]
I am using DataTables for this (https://datatables.net/examples/ajax/deep.html) and have tried doing what it describes. It doesnt really cover reading arrays within arrays though.
To select an array within an array I have tried to follow the datatables example and done the following:
$(document).ready(function() {
$('#example').DataTable({
//sort on col 3 desc
"order": [3, 'desc'], //order by date
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"ajax": {
"type": 'GET',
"dataType": 'json',
"lengthChange": true,
"contentType": 'application/json; charset=utf-8',
"url": "jsonlocation",
"deferRender": true,
"dataSrc": ""
},
"buttons": [ 'copy', 'excel',
{ extend: 'colvis', columns: [0,1,2,3,4,5,6]}
],
"dom": 'Bfrtip',
"columns": [
{ data: 'metadata.15.values.0', "defaultContent": "-" },
{ data: 'title', "defaultContent": "-" },
{ data: 'metadata.16.values.0', "defaultContent": "-" },
{ data: 'lastEdition', "defaultContent": "-" },
{ data: 'lang', "defaultContent": "-" },
{ data: 'version', "defaultContent": "-" },
{ data: 'readerUrl', "defaultContent": "-" },
{ data: 'readerUrl', "defaultContent": "-" },
],
"columnDefs": [{
"targets": [5],
"render": function(data, type, row, meta) {
return 'Click';
}
},
{
"targets": [7],
"visible": false,
"searchable": true
}
]
});
}
);
A table is created, but not populated, and shows no errors in console.
Has anyone any experience using dataTables for this purpose?
Thanks
Check if this helps you out.
var data = {
"title": "SampleTitle",
"lang": "en-US",
"lastEdition": "2020-07-28",
"version": "1.0",
"metadata": [
{
"key": "sampleKey1",
"label": "sampleLabel1",
"values": ["sampleValue1"]
},
{
"key": "sampleKey2",
"label": "sampleLabel2",
"values": ["sampleValue2"]
}]
}
var result = { data: data.metadata[1].values[0], "defaultContent": "-" }
console.log(result);
Your JSON data structure is an array - everything is contained in a [...] - therefore DataTables can iterate over this array to generate its table rows.
Here is an example with everything removed from your code except for the column data definitions (and column titles):
<script type="text/javascript">
$(document).ready(function() {
$('#example').DataTable({
ajax: {
// my test URL:
url: 'http://localhost:7000/sample2',
dataSrc: ''
},
"columns": [
{ title: 'Title', data: 'title' },
{ title: 'Language', data: 'lang' },
{ title: 'Key', data: 'metadata[0].key' },
{ title: 'Label', data: 'metadata[0].label' },
{ title: 'First Value', data: 'metadata[0].values[0]' }
]
} );
} );
</script>
This generates a table which looks like this:
How does this work?
By default, DataTables expects the JSON structure to be as one of the following:
An object containing an array of other objects:
{ "data": [ {...},{...},... ] }
An object containing an array of arrays:
{ "data": [ [...],[...],... ] }
In both these cases, the array has a name (in this case data).
In your case, as already noted, your data is just a plain array of objects:
[ {...}, {...},... ]
Because the array has no name, we need to use dataSrc: '' in our DataTable definition, to indicate this lack of a name.
After that, you can reference the values you need to display, for example data: 'title'.
For the metadata section, that is itself a label referring to an array of objects:
"metadata": [ {...} ]
However, in this case the array only contains one object. We can refer to that first object in the metadata array using [0] - and then we can access the values in that object - for example, by using: data: 'metadata[0].label'.

How to access values of other json objects in single table of datatable library?

I am trying to display data and view/edit/delete buttons using datatables.
I am getting user data and permission using two objects like this:
]
{
"data": [
{
"userid": "1",
"username": "John",
"email": "john#gmail.com",
"userrole": "SYSTEM VENDOR",
"isactive": "Y",
"activationstat": "deactivate",
"activationmsg": "Deactivate"
}
],
"perm":
{
"read": "y",
"edit": "y",
"delete": "n"
}
}
The button needs to be rendered for each row. Datatables code is as:
$('#dt-user').DataTable({
dom: 'lBfrtip',
buttons: [
{
extend: 'copyHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'csvHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'excelHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'pdfHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'print',
exportOptions: {
columns: ':visible'
}
},
'colvis'
],
ajax: baseURL + 'user/list-user-aj',
columns: [
{
"data": "id",
render: function (data, type, row, meta) {
return meta.row + meta.settings._iDisplayStart + 1;
}
},
{ data: 'username' },
{ data: 'email' },
{ data: 'userrole' },
{ data: 'isactive' }
],
responsive: {
details: false
}
});
How can I access the "perm" JSON object for checking its values for displaying buttons for edit, delete, print etc?
Short answer: You will not be able to get "perm" object within datatables initialization code. Datatables initialization code only works with "data" array from JSON.
However, here are two possible solutions to your situation:
Option 1:
If the "perm" object is going to be common for all elements (users) in the "data" array in JSON, like follows:
{
"data": [
{
"userid": "1",
"username": "John",
"email": "john#gmail.com",
"userrole": "SYSTEM VENDOR",
"isactive": "Y",
"activationstat": "deactivate",
"activationmsg": "Deactivate"
},
{
"userid": "2",
"username": "John2",
"email": "john2#gmail.com",
"userrole": "SYSTEM VENDOR2",
"isactive": "Y",
"activationstat": "deactivate",
"activationmsg": "Deactivate"
}
<!-- and maybe some more objects-->
],
"perm":
{
"read": "y",
"edit": "y",
"delete": "n"
}
}
then you can access the perm object like below: (and that would be outside of Datatables definition)
var permissions;
userDatatable.on('xhr', function () {
var json = userDatatable.ajax.json();
var permissions = json.perm;
});
where userDatatable will be the global javascript variable when you initialize Datatables like below:
var userDatatable = $('#dt-user').DataTable({ //......and all your code
Then inside your columns definition, you can access perm object and render buttons like this:
columns:[
{
data:null,
"render": function(data, type, row, meta){
if(perm.delete === 'y'){
return "<button class='deleteButton'> Delete </button>";
}
}
}
]
Make sure javascript variable "permissions" is global and visible to your Datatables initialization code. This will get you the Delete button, but you will have to write additional Javascript/JQuery code to trigger the Datatables Editor's AJAX call to delete the row; both at backend and from the grid.
Option 2: You could modify your server-side code to return JSON such that it will have permissions object within each element of the "data" array:
{
"data": [
{
"userid": "1",
"username": "John",
"email": "john#gmail.com",
"userrole": "SYSTEM VENDOR",
"isactive": "Y",
"activationstat": "deactivate",
"activationmsg": "Deactivate",
"perm":
{
"read": "y",
"edit": "y",
"delete": "n"
}
},
{
"userid": "2",
"username": "John2",
"email": "john2#gmail.com",
"userrole": "SYSTEM VENDOR2",
"isactive": "Y",
"activationstat": "deactivate",
"activationmsg": "Deactivate",
"perm":
{
"read": "y",
"edit": "y",
"delete": "n"
}
}
<!-- and maybe some more objects-->
]
}
With this second option, you could access perm object within the "render" function using "row.perm.delete" property.
Hope this help!

how to fetch my syllables so I can console log them

the JSON looks like this:
{
"main_object": {
"id": "new",
"getExerciseTitle": "TestAfterCodeCleaning",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "TestAfterCodeCleaning",
"language": "nl_NL",
"exercises": [
{
"word": "testikels",
"syllables": [
"test",
"ikels",
"",
""
]
}
]
},
"dataType": "json"
}
}
This is how I try to fetch the syllables so I can console.log() them:
var jsyl = json.main_object.main_object.exercises.syllables;
the problem however: This shows in my console.log() undefined. Why and how?
The complete code looks like this:
function prepareCheck() {
$.getJSON('json_files/jsonData_' + ID + '.json', function(json) {
$(document).on('keyup', '.syl-input', function() {
var syllableval = $(idsyll).val();
var jsyl = json.main_object.main_object.exercises.syllables;
});
});
}
Note: The JSON has one syllables, because I thought it would be easier for you to read, however what should be done to fetch all the syllables (in case there are more then one array of syllables).
Use exercises[0] instead of exercises because exercises is an array of objects in this case only having one item at index 0.
var jsyl = json.main_object.main_object.exercises[0].syllables;
var json = {
"main_object": {
"id": "new",
"getExerciseTitle": "TestAfterCodeCleaning",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "TestAfterCodeCleaning",
"language": "nl_NL",
"exercises": [
{
"word": "testikels",
"syllables": [
"test",
"ikels",
"",
""
]
}
]
},
"dataType": "json"
}
}
var jsyl = json.main_object.main_object.exercises[0].syllables;
console.log(jsyl); // [ 'test', 'ikels', '', '' ]

Populate javascript.datatables with json?

I am trying to have a javascript.datatable (http://www.datatables.net/) show a dataset which I have passed through as a json string.
$(document).ready(function () {
$('#Reports').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="ReportsTable"></table>');
var data = <%=jsonResult%>;
$('#ReportsTable').dataTable({
"data": data,
"columns": [
{ "title": "id" },
{ "title": "name" },
{ "title": "regAndId" },
{ "title": "type" },
{ "title": "timeStamp" }
]
});
});
My jsonResult or data variable looks as follows:
{
"reports": [
{
"id": "421b4b9b-63d5-4fe2-a929-a85d9fe9d2ef",
"name": "TAMANYA PROPERTIES",
"regAndId": "1989/011313/23",
"timeStamp": "2014/10/31 01:57:51 PM",
"type": "Company"
},
{
"id": "56751c5d-84b2-463a-95be-9feb2fa02c10",
"name": "TESTA PROPERTY COMPANY PTY",
"regAndId": "1980/004250/07",
"timeStamp": "2014/10/31 10:29:09 AM",
"type": "Company"
}
]
}
The error I am getting is:
Uncaught TypeError: undefined is not a function
This could happens if the DataTable library is not loaded properly. First jQuery should be loaded and then dataTables.
Assuming you have properly included both jQuery and DataTables libraries, you need to configure the columns according to your data structure. Something like this should work for you:
$(document).ready(function () {
$('#Reports').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="ReportsTable"></table>');
var data = {
"reports": [
{
"id": "421b4b9b-63d5-4fe2-a929-a85d9fe9d2ef",
"name": "TAMANYA PROPERTIES",
"regAndId": "1989/011313/23",
"timeStamp": "2014/10/31 01:57:51 PM",
"type": "Company"
},
{
"id": "56751c5d-84b2-463a-95be-9feb2fa02c10",
"name": "TESTA PROPERTY COMPANY PTY",
"regAndId": "1980/004250/07",
"timeStamp": "2014/10/31 10:29:09 AM",
"type": "Company"
}
]
};
$('#ReportsTable').dataTable({
"data": data.reports,
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "regAndId" },
{ "data": "type" },
{ "data": "timeStamp" }
]
});
});
See demo
Try change this
var data = <%=jsonResult%>;
to
var data = '<%=jsonResult%>';
Note the quotes.
This is needed as the content you are assigning is expecting json string and not just an object/function.

Cannot Use JSON.stringify in aaData for Jquery DataTables

I am using jquery DataTables to bind my JSON data to the Table, however when I specify the JSON object to the 'aaData' option of the DataTable, it throws me this error:
"DataTables warning (table id = 'tblReceipt'): Requested unknown parameter '1' from the data source for row 0"
My JSON object looks like this:
var r = [
{ "Vid": "1", "Receiptno": "AFL123", "Type": "3", "Branch": "AFL", "Date": "23/11/2013" },
{ "Vid": "2", "Receiptno": "AFL124", "Type": "4", "Branch": "AFL", "Date": "24/11/2013" },
{ "Vid": "3", "Receiptno": "AFL125", "Type": "6", "Branch": "AFL", "Date": "25/11/2013" },
];
I am passing it to DataTables like this:
$("#tblReceipt").dataTable({
"aaData": JSON.stringify(r),
"bJQueryUI": true,
"bDestroy": true,
"iDisplayLength": 50,
"bProcessing": true,
"aaSorting": [[0, 'desc']],
"aoColumns": [
{ "mData": "Vid" },
{ "mData": "Receiptno" },
{ "mData": "Type" },
{ "mData": "Branch" },
{ "mData": "Date" },
],
"oLanguage": {
"sProcessing": "Fetching Data, Please wait..."
},
});
Any help would be greatly appreciated!
Just replace "aaData": JSON.stringify(r), with "aaData": r,.
Working demo: http://jsfiddle.net/qMPzh/1/

Categories

Resources