explanation
You need to populate the table (or other DOMElement element) in HTML with your JavaScript, which runs dynamically after loading the page and receiving your JSON object.
You want to iterate over an object. The best way to do this is for loop and make sure that our cyclic variable remains valid for the length of our object (all its attributes).
The best way to get the length of a JSON object is to use myJSONObject.length : you select the keys myJSONObject and return their number.
You can access the values ββstored in your JSON object as follows in a for loop (assuming the particular loop variable is called i ): myJSONObject[i].theAttributeIWantToGet
Price Formatting Breakdown
Now these prices should have the correct format, right? Therefore, we will check to see if any value attribute has less than 2 characters after . inside them. If they do, we will add another decimal 0 . We also add $ before writing the formatted value. Here is a breakdown of how this works:
Also: Why am I using innerHTML instead of appendChild() .
Decision
HTML
<table> <tbody id="tbody"></tbody> </table>
Json
[{ "key": "apple", "value": 1.90 }, { "key": "berry", "value": 1.7 }, { "key": "banana", "value": 1.5 }, { "key": "cherry", "value": 1.2 }]
Javascript
Note. In this case, the JSON object will be called obj .
var tbody = document.getElementById('tbody'); for (var i = 0; i < obj.length; i++) { var tr = "<tr>"; if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2) obj[i].value += "0"; tr += "<td>" + obj[i].key + "</td>" + "<td>$" + obj[i].value.toString() + "</td></tr>"; tbody.innerHTML += tr; }
source share