简体   繁体   中英

Reading arrays within arrays of a json file

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

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);

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:

在此处输入图像描述

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' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM