0

I am building a site which will output data from a JSON file into a table, but I am having issues getting the content to output. This JSON file is generated from another site which surfaces documentation, while my site just creates a table for easy searching of those docs.

SAMPLE JSON for 2 docs:

    [{
        "title": "SampleTitleA",
        "lang": "en-US",
        "lastEdition": "2020-07-28",
        "version": "1.0",
        "metadata": [
        {
            "key": "sampleKeyA1",
            "label": "sampleLabelA1",
            "values": ["sampleValueA1"]
        },
        {
            "key": "sampleKeyA2",
            "label": "sampleLabelA2",
            "values": ["sampleValueA2"]
        }]
    },
    {
        "title": "SampleTitleB",
        "lang": "en-US",
        "lastEdition": "2020-07-28",
        "version": "1.0",
        "metadata": [
        {
            "key": "sampleKeyB1",
            "label": "sampleLabelB1",
            "values": ["sampleValueB1"]
        },
        {
            "key": "sampleKeyB2",
            "label": "sampleLabelB2",
            "values": ["sampleValueB2"]
        }]
    }]

I am using DataTables for this (https://datatables.net/examples/ajax/deep.html) and have tried doing what it describes. It doesnt really cover reading arrays within arrays though.

To select an array within an array I have tried to follow the datatables example and done the following:

    $(document).ready(function() {
    $('#example').DataTable({
        //sort on col 3 desc
        "order": [3, 'desc'], //order by date
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "ajax": {
            "type": 'GET',
            "dataType": 'json',
            "lengthChange": true,
            "contentType": 'application/json; charset=utf-8',
            "url": "jsonlocation",
            "deferRender": true,
            "dataSrc": ""
        },
        
        "buttons": [ 'copy', 'excel',
            { extend: 'colvis', columns: [0,1,2,3,4,5,6]}
        ],
        "dom": 'Bfrtip',
        "columns": [
            { data: 'metadata.15.values.0', "defaultContent": "-" },
            { data: 'title', "defaultContent": "-" },
            { data: 'metadata.16.values.0', "defaultContent": "-" },
            { data: 'lastEdition', "defaultContent": "-" },
            { data: 'lang', "defaultContent": "-" },
            { data: 'version', "defaultContent": "-" },
            { data: 'readerUrl', "defaultContent": "-" },
            { data: 'readerUrl', "defaultContent": "-" },
        ],
        "columnDefs": [{
                "targets": [5],
                "render": function(data, type, row, meta) {
                    return '<a href="' + data + '">Click</a>';
                }
            },
            {
                "targets": [7],
                "visible": false,
                "searchable": true
            }
        ]
    });
}
);

A table is created, but not populated, and shows no errors in console. Has anyone any experience using dataTables for this purpose?

Thanks

4
  • Please add your datatable code. Commented Jul 28, 2020 at 10:08
  • You mention that the JSON in your question represents a single document. So I assume the actual JSON consists of many such objects in an array - is that correct? So, for example what would the complete JSON look like for 2 documents? We would need to see that overall structure to provide relevant guidance. Thank you. Commented Jul 28, 2020 at 17:08
  • Ive updated to include 2 sample docs in array Commented Jul 29, 2020 at 9:39
  • Thank you - that helped. Answer posted. Commented Jul 29, 2020 at 13:01

2 Answers 2

1

Check if this helps you out.

var data = {
    "title": "SampleTitle",
    "lang": "en-US",
    "lastEdition": "2020-07-28",
    "version": "1.0",
    "metadata": [
    {
        "key": "sampleKey1",
        "label": "sampleLabel1",
        "values": ["sampleValue1"]
    },
    {
        "key": "sampleKey2",
        "label": "sampleLabel2",
        "values": ["sampleValue2"]
    }]
}

var result = { data: data.metadata[1].values[0], "defaultContent": "-" }
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

Your JSON data structure is an array - everything is contained in a [...] - therefore DataTables can iterate over this array to generate its table rows.

Here is an example with everything removed from your code except for the column data definitions (and column titles):

<script type="text/javascript">

 $(document).ready(function() {

    $('#example').DataTable({
        ajax: {
          // my test URL:
          url: 'http://localhost:7000/sample2',
          dataSrc: ''
        },
        "columns": [
          { title: 'Title', data: 'title' },
          { title: 'Language', data: 'lang' },
          { title: 'Key', data: 'metadata[0].key' },
          { title: 'Label', data: 'metadata[0].label' },
          { title: 'First Value', data: 'metadata[0].values[0]' }
        ]
    } );

  } );

</script>

This generates a table which looks like this:

enter image description here

How does this work?

By default, DataTables expects the JSON structure to be as one of the following:

  1. An object containing an array of other objects:
{ "data": [ {...},{...},... ] }
  1. An object containing an array of arrays:
{ "data": [ [...],[...],... ] }

In both these cases, the array has a name (in this case data).

In your case, as already noted, your data is just a plain array of objects:

[ {...}, {...},... ]

Because the array has no name, we need to use dataSrc: '' in our DataTable definition, to indicate this lack of a name.

After that, you can reference the values you need to display, for example data: 'title'.

For the metadata section, that is itself a label referring to an array of objects:

"metadata": [ {...} ]

However, in this case the array only contains one object. We can refer to that first object in the metadata array using [0] - and then we can access the values in that object - for example, by using: data: 'metadata[0].label'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.