Nested JSON data and the dataSrc property

Nested JSON data and the dataSrc property

remiegoremiego Posts: 19Questions: 2Answers: 0

I have a requirement to consume some JSON in the following shape:

{
    "responseList": [{
        "eventList": [{
            "eventId": "1",
            "eventInfo": "first",
            "attributes": {
                "status": "OPEN",
                "severity": "HIGH",
            }
        }, {
            "eventId": "2",
            "eventInfo": "second",
            "attributes": {
                "status": "CLOSED",
                "severity": "LOW",
            }
        }
    }]
}

I'm not sure how to setup the dataSrc attribute to point to the evenList range. I've tried "eventList", "responseList.eventList" and in columns having:

"columns":[
    {"data":"responseList.eventList.eventId"}
]

I'm not currently getting any errors but I'm failing to bind the data, my html has been stripped back to contain a single column to try and get it to work.

    <table id="eventData" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>EventId</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>EventId</th>
            </tr>
        </tfoot>
    </table>

Current javascript

$(document).ready(function() {
    $('#eventData').DataTable( {
        'ajax': {
            'url': 'data.json',
            'dataSrc': 'eventList',
            'columns': [
                {'eventList': 'eventId'}
            ]
        }
    } );
} );

This question has accepted answers - jump to:

Answers

  • allanallan Posts: 61,650Questions: 1Answers: 10,094 Site admin
    Answer ✓

    dataSrc: "responseList.0.eventList" should do it. It will get the first element of the responseList array. Is that array only ever length 1?

    Allan

  • remiegoremiego Posts: 19Questions: 2Answers: 0

    Yes Allan, always a single element container, its so obvious when you put it down. I've looked at other examples and seen this array element notation but never joined the dots. Thanks and apologies for the dumb Q.

  • remiegoremiego Posts: 19Questions: 2Answers: 0

    Still struggling with this, I can see in Chrome that I'm getting the data from the ajax call but am singularly unable to bind this to the datatable. I have dataSrc set to "responseList.0.eventList".

    I can't get any columns to bind. I have cut my table and data down to a single field "eventId" but can't see how the columns should be defined. I'm getting a Requested unknown paramater '0' for row 0, column 0. I've tried "data":"eventId" and other derivatives but just can't get this working.

    $(document).ready(function() {
        $('#eventData').DataTable( {
            'ajax': {
                'url': 'data.json',
                'dataSrc': 'responseList.0.eventList',
                'columns': [
                    {'eventList': 'eventId'}
                ]
            }
        } );
    } );
    
  • remiegoremiego Posts: 19Questions: 2Answers: 0

    Ok, this is weird but looks like my data is being returned from the server as an array, using JSON.Stringify brings it in as desired, still not binding to the table but have moved on.

  • remiegoremiego Posts: 19Questions: 2Answers: 0

    Really looking for someone to plug a gap for me....

    Have got the following defined:

                'type': 'POST',
                'dataSrc': function(json){
                    return JSON.stringify(json.responseList[0].eventList);
                },
                'columns': [
                    {'data': 'eventId'},
                    {'data': 'routingInfo'}
                ]
    

    This dataSrc function returns the following (output cut for brevity) which looks like good JSON to me.

    [{
        "eventId": "mc.prod_bemview_01.17bc247d.0",
        "routingInfo": "prod_bemview_01",
        "eventDate": 0,
        "attributes": {
            "CLASS": "BPPM_INFRASTRUCTURE",
            "status": "OPEN",
            "mc_ueid": "mc.prod_bemview_01.17bc247d.0",
            "severity": "OK",
            "mc_priority": "PRIORITY_5",
            "msg": "standalone cell prod_bemview_01 is OK"
        }
    }, {
        "eventId": "mc.prod_bemview_01.17bc247d.2",
        "routingInfo": "prod_bemview_01",
        "eventDate": 0,
        "attributes": {
            "CLASS": "BPPM_INFRASTRUCTURE",
            "status": "OPEN",
            "mc_ueid": "mc.prod_bemview_01.17bc247d.2",
            "severity": "OK",
            "mc_priority": "PRIORITY_5",
            "msg": "cell cluster prod_int_03 is OK"
        }
    }]
    
    

    My HTML is as:

        <table id="eventData" class="display" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th>EventId</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <th>EventId</th>
                    <th>Status</th>
                </tr>
            </tfoot>
        </table>
    

    So my question is how to I get eventId and status displayed? I've tried:

    {"data":"eventId},
    {"data":"attributes.status"}
    

    I still cant seem to even get a single field displayed, I'm really missing something fundamental.

  • allanallan Posts: 61,650Questions: 1Answers: 10,094 Site admin

    Ok, this is weird but looks like my data is being returned from the server as an array, using JSON.Stringify brings it in as desired

    That's weird.

    Do you have a link to the page you can give me and I'll check it out.

    Allan

  • remiegoremiego Posts: 19Questions: 2Answers: 0

    Hi Allan, unfortunately this is all internal, the data comes back as JSON when using postman so I think its something that I'm doing wrong. Anyway, my major issue is that I can't seem to bind a field to the table. I've done this in the past so not sure what the issue is.

    After doing some more testing, if I do:

    JSON.stringify(json.responseList[0].eventList)

    this returns JSON ok,

    If I do it against the entire response:

    JSON.stringify(json)

    I get an error, which indicates that stringify won't work as the data is already json format.

    When I look through the debugging tools it looks like a javascript array (maybe its my lack of familiarity with chrome dev tools that's the issue).

    With my data and column definition in my previous post, should that be working?

  • remiegoremiego Posts: 19Questions: 2Answers: 0

    Have attached the success function from my Ajax request, it shows the "data" as an object, I'd have thought JSON would show as a string?

  • remiegoremiego Posts: 19Questions: 2Answers: 0

    Ok, more debugging, it appears my:

    'dataSrc': function....

    is never being triggered (I added a console.log() to the function and it never displays).

    So, is it possible it's my request that's causing the issue? This is pretty much the entire script (obfuscated):

    $(document).ready(function() {
        $('#eventData').DataTable( {
            'ajax': {
                'url': 'data.json',
                'beforeSend': function(xhr){
                   // Check Authorization validity
                   // make new authorization request if necessary
                   // Get the current Auth data
                   var authToken=$.cookie("authToken");
                   var authExpires=$.cookie("authExpires");
                   // Check if we need to generate a new authorization token
                   if ((!authExpires) || (Date.parse(authExpires) < Date.now())){
                      // Need new token
                      $.ajax({
                          url: '/bppmws/api/authenticate/login',
                          type: 'POST',
                          // Need to wait for this to complete
                          async: false,
                          contentType: 'application/x-www-form-urlencoded',
                          dataType: 'json',
                          data: 'username=XXXXXX&password=XXXXXX',
                          success: function(data){
                              authToken=data.response.authToken;
                              authExpires=data.response.expires;
                              // update cookies
                              $.cookie("authToken",authToken);
                              $.cookie("authExpires",authExpires);
                          },
                          failure: function(data){
                              toastr.error('error seeking authorization.');
                              return false;
                          }
                      })
                   }
    
                   xhr.setRequestHeader('Authorization','authToken ' + authToken);
    
                },
                'success': function(data){
                    toastr.info('data loaded');
                },
                'contentType': 'application/json',
                'data': function(d) {
                    return JSON.stringify({'slotList':['mc_ueid','severity','msg','mc_priority','status'],'criteria':{'operator':'EQUALS','identifier':'status','value': 'OPEN'}});
                },
                'type': 'POST',
    //            'dataSrc': 'responseList.0.eventList',
                'dataSrc': function(json){
                      console.log('here' + json);
                },
                'columns': [
                    {'data': 'eventId'},
                    {'data': 'routingInfo'}
    
                ]
            }
        } );
    } );
                   
    
  • remiegoremiego Posts: 19Questions: 2Answers: 0

    Ok, forget last post, issues were down to me introducing a success function... back to square 1 again.

  • remiegoremiego Posts: 19Questions: 2Answers: 0

    I think I see where my problem resides. I'm using:

                'data': function() {
                    return JSON.stringify({'slotList':['mc_ueid','severity','msg','mc_priority','status'],'criteria':{'operator':'EQUALS','identifier':'status','value': 'OPEN'}});
                },
    

    as I'm "POSTING" this data as part of my AJAX submission, problem is "data" seems to be used for the response data also so will I need to use a callback to set data after the response is received? If that's the case where do I set the callback up, which event do I use? etc.,

  • allanallan Posts: 61,650Questions: 1Answers: 10,094 Site admin
    Answer ✓

    problem is "data" seems to be used for the response data also

    It shouldn't be. The ajax.data function will only be called when the Ajax request is submitted. ajax.dataSrc will be used when the server responds to that request.

    issues were down to me introducing a success function

    Yeah - you can't do that (yet) I'm afraid. You'd need to use a callback if you need to know when the Ajax response has been returned.

    Allan

  • remiegoremiego Posts: 19Questions: 2Answers: 0

    Thanks Allan, been stripping this down and cutting nearly all functionality out. I'm unable to get even this config working:

                'dataSrc': function(json){
                      return JSON.parse('[{"eventId":"mc","routingInfo":"prodbemview01"}]');
                },
    
                'columns': [
                    {'data': 'eventId'},
                    {'data': 'routingInfo'}
                ]
    

    The dataSrc function runs and the attachment shows how that looks in Chrome dev.

    What the hell am I missing here????

  • remiegoremiego Posts: 19Questions: 2Answers: 0

    Anyone have any ideas on why the last post wouldn't work? I get "Requested unknown parameter '0' for row 0, column 0" message even with this....

  • remiegoremiego Posts: 19Questions: 2Answers: 0
    edited October 2016

    I can't really make this any simpler, I'm 100% I'm doing something really obviously dumb.

    Here are my setting.
    HTML

    <!DOCTYPE html>
    <html>
      <head>
        <title>Home</title>
            <script src="js/jquery.2.2.4.js"></script>
    
            <link type="text/css" rel="stylesheet" href="css/jquery.dataTables.min.css" />
            <link type="text/css" rel="stylesheet" href="css/dataTables.boostrap.min.css" />
    
            <script type="text/javascript" src="js/jquery.dataTables.1.10.12.min.js"></script>
            <script type="text/javascript" src="bppm-dataTable.js"></script>
    
      </head>
      <body>
        <table id="eventData" class="display" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th>EventId</th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <th>EventId</th>
                </tr>
            </tfoot>
        </table>
      </body>
    </html>
    

    Script

    $(document).ready(function() {
    $('#eventData').DataTable( {
            'ajax': {
                'url': 'data1.json',
                'contentType': 'application/json',
                'data': function() {
                    return JSON.stringify({'slotList':['mc_ueid','severity','msg','mc_priority','status'],'criteria':{'operator':'EQUALS','identifier':'status','value': 'OPEN'}});
                },
                'type': 'POST',
                'dataSrc': function(data){
                      return JSON.parse('[{"eventId":"mc"}]');
                },
                'columns': [
                    {'data': 0}
                ]
            }
        });
    });
    
    

    And the JSON thats contained in the data1.json:

    {
            "responseList": [{
                    "eventList": [{
                            "eventId": "mc"
                     }]
            }]
    }
    

    Still getting the "Requested unknown parameter '0' for row 0, column 0" message. HELP!!!!

  • allanallan Posts: 61,650Questions: 1Answers: 10,094 Site admin
    Answer ✓

    Took me a minute there, but there are two issues with the code:

    1. The columns array should not be nested inside the ajax option!
    2. data: 0 should be data: 'eventId' if you want to read the eventId property.

    Example: http://live.datatables.net/lelexuki/1/edit .

    Allan

  • remiegoremiego Posts: 19Questions: 2Answers: 0

    Arrgggghhhh, that was it, a full day wasted. I should have checked that after I put a render event against one of the data configs that didn't fire. The data:0 was me just clutching at straws. MUCH appreciated Allan!

This discussion has been closed.