简体   繁体   中英

Issues while displaying JSON data in table

I'm having an issue while displaying json data in an html table. I believe it has to do with the fact that my json's formatted really strange (i can't change it) Thanks in advance.

{"name":["instance-5","instance-6"],"id"["1178823664323071067","5394281241544297728"],"ip":["35.189.8.115","35.201.16.102"],"status":["RUNNING","RUNNING"]}

<script> 

$( document ).ready(function() {
$.ajax({
    url: '/api/instance/list',
    type: 'get',
    dataType: 'json',
    error: function(data){
    },
    success: function(data){
        var tr = $('<tr>');
        tr.append('<td>' + data.name + '<td>');
        tr.append('<td>' + data.id + '<td>');
        tr.append('<td>' + data.ip + '<td>');
        tr.append('<td>' + data.status + '<td>');


        $('#application-table').append(tr);           
    }
});
});

</script>

<table id="application-table" class="aui">
<thead>
    <tr>
        <th width="20%">Instance Name</th>
        <th width="20%">ID</th>
        <th width="20%">IP</th>
        <th width="5%">Status</th>

    </tr>
</thead>

Your response is formatted such that each property is its own array, presumably meaning that name[0] is related to all the other [0] indexed items in the other arrays.

Therefore to achieve what you require you can loop over the response and put all the values within the properties at the same index within the new row, like this:

 var data = { "name": ["instance-5", "instance-6"], "id": ["1178823664323071067", "5394281241544297728"], "ip": ["35.189.8.115", "35.201.16.102"], "status": ["RUNNING", "RUNNING"] } for (var i = 0; i < data.name.length; i++) { var tr = $('<tr>'); tr.append('<td>' + data.name[i] + '<td>'); tr.append('<td>' + data.id[i] + '<td>'); tr.append('<td>' + data.ip[i] + '<td>'); tr.append('<td>' + data.status[i] + '<td>'); $('#application-table').append(tr); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="application-table"></table> 

That said, I'd recommend finding a way to change your response structure to relate row data in each item of a single array, something like this:

 var data = [{ "name": "instance-5", "id": "1178823664323071067", "ip": "35.189.8.115", "status": "RUNNING" }, { "name": "instance-6", "id": "1178823664323071067", "ip": "35.201.16.102", "status": "RUNNING" }] var html = data.map(function(row) { return `<tr><td>${row.name}</td><td>${row.id}</td><td>${row.ip}</td><td>${row.status}</td></tr>`; }); $('#application-table').append(html.join('')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="application-table"></table> 

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