Datatables parsing nested json with ajax that has not data header object

Viewed 106

I'm trying to parse a JSON object I'm making in Python and populate it in Datatables using ajax. It's not parsing the data into the columns but I suspect it could be because of my JSON structure since it doesn't have the "data" header object? Am I accessing the data correcting in my ajax ?

Here's my AJAX section

$(document).ready(function() {
        $.fn.dataTable.ext.errMode = 'none';
        var table = $('#ce_table').DataTable( {
        "processing": true,
        "ajax": "/api/1.0/agents",
        "columns": [
            { "data": "machine.hostname" },
            { "data": "machine.epm" }
        ]
    } );
    });

This is what my data structure looks like

[
    {
        "machine": {
            "hostame": "machine0101",
            "epm": "0"
        }
    },
    {
        "machine": {
            "hostame": "machine0202",
            "epm": "1"
        }
    }
]
1 Answers

The problem was in fact the structure of the JSON, seems you are limited in a way when you do not have a parent object like "data" in the JSON structure.

Sample of the new JSON:

{
    "data": [
        {
            "machine": {
                "hostname": "machine111"
            },
            "content": {
                "epm": "0"
            }
        },
        {
            "machine": {
                "hostname": "machine222"
            },
            "content": {
                "epm": "1"
            }
        }
    ]
}

Which was achieved by changing the python code that builds the JSON, see below:

def agents_api():
    _tmp = []
    _dict = {}
    _final_dict = {}
    _nested_machine = {}
    _nested_content = {}
    epm_result = #A list ('machine111', machine999')
    machine_result = #A list ('machine111', machine222')
    for machine in machine_result:
        if machine in epm_result:
            _nested_machine["hostname"] = machine
            _nested_content['epm'] = "1"
        else:
            _nested_machine["hostname"] = machine
            _nested_content['epm'] = "0"
        _dict['machine'] = _nested_machine
        _dict['content'] = _nested_content
        _tmp.append(_dict) <--- put it together in a list, this is the 'nested' part
    _final_dict['data'] = _tmp <--- create the parent "data" object
    json_data = dumps(_final_dict) <--- convert to JSON object
    print(json_data)
    return json_data <--- send back
Related