Datatables with nested JSON

Datatables with nested JSON

SilicanSilican Posts: 2Questions: 1Answers: 0

Hello,

I'm having trouble populating a table, accessing a text file that has JSON like this:

{
    "1000": {
        "country": "US",
        "eventid": 1000,
        "venue": "San Francisco, USA"
    },
    "2000": {
        "country": "DE",
        "eventid": 2000,
        "venue": "Munich, Germany"
    },
    "3000": {
        "country": "GB",
        "eventid": 3000,
        "venue": "UK (Market House)"
    }
}

I have followed the examples on this site and this is my JavaScript to load the data back:

$(document).ready(function() {
    $('#example').dataTable( {
        "processing": true,
        "ajax": 'json.txt',
        "columns": [
            { "data": "country" },
            { "data": "eventid" },
            { "data": "venue" }
        ]
    } );
} );

What am I doing wrong here ? Can someone look into this please ?

This question has an accepted answers - jump to answer

Answers

  • SilicanSilican Posts: 2Questions: 1Answers: 0
    edited October 2014

    I ended up adding a custom function to change the JSON value as an array

    $(document).ready(function () {
        $('#example').dataTable({
            "processing": true,
            "ajax": {
                "url": 'json.txt',
                "dataSrc": function (json) {
                    var arr = Object.keys(json).map(function(k) { return json[k] });
                    return arr;
                }
            },
            "columnDefs": [
                {
                    "targets": [2],
                    "visible": true,
                    "searchable": true
                }
            ],
            "columns": [
                {
                    "data": "eventid"
                },
                {
                    "data": "country"
                },
                {
                    "data": "venue"
                }
            ]
        });
    });
    
  • allanallan Posts: 61,734Questions: 1Answers: 10,111 Site admin
    Answer ✓

    Hi,

    What you could do is use data: '1000.country' to access the data from that parameter. I'm not sure if you want that? DataTables needs the data in an array for multiple rows - it will not accept an object, so if the JSON is only an object and each property at the top level is an array, you would need to do has you have done and reformat the data.

    Allan

This discussion has been closed.