JSON key value pairs to HTML table in JS

I have an endpoint that I’ve parsed and want to iterate through the data placing the key in one table cell and the value in another. I want to loop through this and display everything one row at a time.

I am new to this so please be gentle.

First of all, welcome. :slight_smile:
We’ll try and be gentle.

Are you trying to put data into an EXISTING table, or are you trying to dynamically CREATE a table? Because that’s two different approaches.

I thought it best to make the header static and just loop through the data and dynamically create the rows from the information. The JSON is very simple and I can’t believe there aren’t good examples out there. The endpoint only returns a key with a value. I wanted to put the key in the first column and the value in the second.

Oh there are examples out there, but it’s more about piecing the examples together into doing what you want them to do specifically.

Let’s look at this:
Table insertRow() Method

That is a clean and simple example of how to create a table row, put two cells in it, and then put data in those cells. We just need to make a couple of replacements in that code for values.

Give it a try, see what you come up with. If you get stuck, come back, show me your code, and we’ll try and figure out where it went wrong.

I’m pretty much at this point:

$("#responseTable").hide();
$("#clickDaButton").click(
function(e){
e.preventDefault();

$.ajax({
url:'/getEndpoint';
type: 'GET',
dataType: 'JSON',
contentType: 'application/json',
success: function(response) {
var showMyData = JSON.stringify(response, null, 4)
$('#responseTable table tbody').html();

I am having the hangup mostly here

}
})
$('#responseTable').show();
});

I know I need to loop through the data and do something like this but don’t how to call the key/value from the JSON properly.

table += '<tr>';
$.each(item_array, function (key, value) {
            table += '<td>' + key[i] + '</td>' + '<td>' + value[i] + '</td>';
        });
 table += '</tr>';

What do you get in the javascript console if you put
console.log(showMyData)
after you declare showMyData?

The endpoint data:

{“ITEM1”:“THINGONE”,“ITEM2”:“THINGTWO”}

okay, so the data is being sent as a single object, not in an array.

Example number 2:
JavaScript for/in Statement

response is an object.

Ignore that last post, i’m an idiot sometimes. It’s an object not an array, x is the key.

I didn’t see two examples or I’m not reading the page right. Also, you lost me. So in the example on the page it shows the JSON being declared as a variable. (person) But this endpoint just spits back data as an object with no title for lack of a better term.

So my question is where do I start my for/in statement inside the .html()?

response is the ‘title’ of your variable. the ajax function has formed it for you.
the ajax has effectively done

let response = {“ITEM1”:“THINGONE”,“ITEM2”:“THINGTWO”}

Use the first example I showed you - your table’s “ID” is responseTable -
Loop through the properties of the response object.
For every property, add a row, insert two cells, put x into the first cell, and put response[x] in the second.

Ah. Gotcha. Thank you. Will do.

I screwed something up big time.

success: function(response) {
var showMyData = JSON.stringify(response, null, 4)
$('#responseTable table tbody').html(
var x;
for (x in response) {
var row = table.insertRow(0);
var keyCell = row.insertCell(0);
var valCell = row.insertCell(1);
keyCell.innerHTML = x;
valCell.innerHTML = response[x];
});
}
})
$('#responseTable').show();
});

I get an Uncaught SyntaxError: Unexpected token ‘var’ when I go to the page. When I click on the button it simply resets the page.

okay, we’re not putting this code inside the html function. Let’s remove that for the moment.

Replace this line:
$('#responseTable table tbody').html(
with this one:
var table = document.getElementById("responseTable");

and we need to clean up the ending a bit. Too many }'s and )'s. What are you using to edit your files?

VSCode

I can’t iterate through using something like this?

success: function(response) {
for (i = 0; i < response.length; i++) {
$.each(response, function(key, val) {
$('#responseTable table tbody').html(`'<tr><td>' + ${key} + '</td><td>' + ${val} + '</td></tr>'`);
});
}

#responseTable is the container div I have the table in because I’m using Bootstrap

I don’t get errors with that code but also don’t get a response.

ah, okay, thats important to know.

If you insist on force-feeding yourself into a jquery corner, you can use .each on the result set, but:

  • '<tr><td>' + ${key} + '</td><td>' + ${val} + '</td></tr>' why you’re now trying to shoehorn in string literals to this i’m not sure.

  • .html()'ing the table body over and over is just going to replace what you’ve got. You could try appending it, so $('#responseTable table tbody').html($('#responseTable table tbody').html()+'<tr><td>' + key + '</td><td>' + val + '</td></tr>');

  • use each or for, not both.

Sorry. I don’t mean to be difficult. I used string literals in a prior lesson and thought they could somehow be relevant.

See, this is kind of the problem, you’re trying to do differential equations before you’ve learned to do addition.

Keep it as simple as you possibly can.