Skip to content
Advertisement

referencing json data in datatables – howto

I have an external json file as follows (fake data);

{
 "data": [
    {
      "id": "1",
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$320,800",
      "start_date": "2011/04/25",
      "office": "Edinburgh",
      "extn": "5421"
    },
    {
      "id": "2",
      "name": "Garrett Winters",
      "position": "Accountant",
      "salary": "$170,750",
      "start_date": "2011/07/25",
      "office": "Tokyo",
      "extn": "8422"
    }
   ]
}

I call the table like below and, as expected it works;

    let myPeople=      $('#myPeople_index').DataTable({                  
        ajax:           '/user_public/people/data/myPeople.txt',
        dataType:       'json', 
        "columns": [
            {"data":"name"},
        ]   
    });

I want to change the array name in the json file to properties and so have revised above as follows;

    let myPeople=      $('#myPeople_index').DataTable({     
        data:           'properties',   
        ajax:           '/user_public/people/data/myPeople.txt',
        dataType:       'json', 
        "columns": [
            {"properties": "name"},
        ]   
    });

and change the datafile to;

{
 "properties": [
    {
      "id": "1",

I get an error as follows;

Uncaught TypeError: Cannot read properties of undefined (reading 'length') 
datatables.min.js:77

I have tried to read the man pages here https://datatables.net/manual/data/#Objects but I am certainly missing something. Any pointers appreciated.

Advertisement

Answer

let myPeople=      $('#myPeople_index').DataTable({     
        data:           'properties',   
        ajax:           '/user_public/people/data/myPeople.txt',
        dataType:       'json', 
        "columns": [
            {"properties": "name"},
        ]   
    });

should be

let myPeople=      $('#myPeople_index').DataTable({     
        ajax: {
          url: '/user_public/people/data/myPeople.txt',
          dataSrc: 'properties'
        }
        dataType:       'json', 
        "columns": [
            {"data": "name"},
        ]   
    });

data is not a key in your data, it’s a specific property in the API.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement