Render child Json data in datatable columns

Render child Json data in datatable columns

Swf1200Swf1200 Posts: 3Questions: 2Answers: 0

I have this JSON response for datatable:

{
    "draw": "1",
    "iTotalRecords": 201,
    "iTotalDisplayRecords": 35,
    "aaData": [
        {
            "id": "265",
            "date": "2022-02-14 01:11:29",
            "ip_address": "127.0.0.1",
            "user_agent": "{\"information\":{\"browser\":\"Firefox\",\"platform\":\"Windows 10\",\"mobile\":\"\"}}",
            "success": "1"
        }
    ]
}

Also, I have child JSON in user_agent and need to show this information in datatable columns.

Datatable JS:

var tableUserActivity = $('#tableUserActivity').DataTable({
    dom: 'rt<"d-md-flex justify-content-between align-items-center" <i> <p>>',
    processing: true,
    serverSide: true,
    responsive: true,
    order: [
        [1, 'desc']
    ],
    ajax: {
        url: '<?= route_to('getUserActivity') ?>',
        method: 'POST',
        'data': function(data) {
            // Read values
            var dateFrom = $('#searchDateFromAlt').val();
            var dateTo = $('#searchDateToAlt').val();
            data.id = '<?= esc($user['id']) ?>';
            // Append to data
            data.filterDateFrom = dateFrom;
            data.filterDateTo = dateTo;
        }
    },
    columnDefs: [{
        orderable: false,
        targets: [0, 2, 3]
    }],
    columns: [{
            'data': 'id',
            'class': 'text-center align-middle'
        },
        {
            'data': 'date',
            'class': 'align-middle'
        },
        {
            data: 'user_agent',
            render: function(data, type, full_row) {
                
                return console.log(full_row.information.browser);
            }
        },
        {
            'data': 'ip_address',
            'class': 'text-center align-middle'
        }
    ]
});

Now in action I see this error:

full_row.information is undefined

How do can I fix this error and show JSON data in columns?!

Answers

  • kthorngrenkthorngren Posts: 20,425Questions: 26Answers: 4,794

    Looks like you will need something like this:

    return full_row.user_agent.information.browser;
    

    Using console.log in the return statement won't work. You can use console.log before the return statement

    Also it looks like the data for user_agent is a JSON string not an object. You might need to use JSON.parse() in the columns.render function first, like this:

                render: function(data, type, full_row) {
                    var user_agent = JSON.parse( full_row.user_agent );                 
                    return user_agent.information.browser;
                }
    

    Kevin

  • Swf1200Swf1200 Posts: 3Questions: 2Answers: 0

    @kthorngren: charm answer, work now!!

Sign In or Register to comment.