Datatables throwing "invalid JSON" error when loading from local file

8k Views Asked by At

I'm trying to pull the following JSON data from a local file into DataTables, but getting an invalid JSON response:

    {
    "data": [
        {
            "accountNumber": "2423",
            "domain": "domain.com",
            "playerClass": "",
            "adTag": ""
        },
        {
            "level": "info",
            "message": "generator ",
            "timestamp": "2015-06-10T15:59:02.803Z"
        }
    ]
}

Using:

    $(document).ready(function () {
        $('#content').dataTable({
            "ajax": 'test.log'
        });
    });

JSFIDDLE

3

There are 3 best solutions below

1
On

It's because you do in fact have invalid JSON. When using datatables, according to the documentation, your data source always needs to be an array: https://www.datatables.net/manual/data

Here is what it should look like:

{
    "data": [
        {
            "accountNumber": "1234",
            "domain": "domain.com",
            "playerClass": "Player",
            "adTag": ""
        },
        {
            "accountNumber": "1234",
            "domain": "domain.com",
            "playerClass": "Player",
            "adTag": ""
        }
    ],
    "level": "info",
    "message": "tag generator ",
    "timestamp": "2015-06-09T21:00:45.776Z"
}

When you create JSON, you should always validate it to make sure it is valid - check out http://jsonlint.org

0
On

You had to put the ajax method call(GET or POST)... Anything like this:

"processing": true,
"serverSide": true,
"ajax": {
    "url": "test.log",
    "type": "POST"
}
0
On

Use this command to catch the error instead alert:

$.fn.dataTable.ext.errMode = 'throw';

From this link