jsondatatabledatatablesdatatables-1.10jquery-datatables-editor

DataTables: Columns with dot (.) in header not displaying correctly


DataTables seems to treat dots (.) as a special character and doesn't display the columns, which have them in the header.

Is there any solution how to keep the dots and use some sort of escape character?

The error is: Requested unknown parameter 'Doc.' for row 0, column 0

My JSON DataTable initializer:

{
    "columns": [
        {
            "data": "Doc.",
            "title": "Doc."
        },
        {
            "data": "Order no.",
            "title": "Order no."
        }
    ],
    "data": [
        {
            "Doc.": "564251422",
            "Order no.": "56421"
        },
        {
            "Doc.": "546546545",
            "Order no.": "98745"
        }
    ]
}

Solution

  • When there is dots in data property names dataTables will look for nested data properties. Like if there was as Doc.<something> property. When you have automated scripts - as you have - the server is distributing JSON not necessarily designed for dataTables, you can "sanitize" the data before passing it to dataTables.

    I took the answer from yesterday and added two functions : sanitizeData and sanitizeColumns. sanitizeData removes all dots and whitespaces from keys, sanitizeColumns remove whitespace and dots from the columns.data definitions :

    $.getJSON('https://api.myjson.com/bins/4z5xd', function(json) {
        //remove whitespace and dots from keys / attribute names    
        function sanitizeData(jsonArray) {
            var newKey;
            jsonArray.forEach(function(item) {
                for (key in item) {
                    newKey = key.replace(/\s/g, '').replace(/\./g, '');
                    if (key != newKey) {
                        item[newKey]=item[key];
                        delete item[key];
                    }     
                }    
            })    
            return jsonArray;
        }            
        //remove whitespace and dots from data : <propName> references
        function sanitizeColumns(jsonArray) {
            var dataProp;
            jsonArray.forEach(function(item) {
                dataProp = item['data'].replace(/\s/g, '').replace(/\./g, '');
                item['data'] = dataProp;
            })
            return jsonArray;
        }    
        json.data = sanitizeData(json.data);
        json.columns = sanitizeColumns(json.columns);    
    
        $('#example').DataTable({
           data : json.data,
           columns : json.columns
        })
    });  
    

    demo -> http://jsfiddle.net/egpxdsq7/