How do you retrieve a JSON object from a local file and display it in a table using jQuery? Here is the content of JSON file (jsondata.json
):
{
"scores" : [ ["3/1/2011", 610],["4/1/2011", 610],["5/1/2011", 610],["6/1/2011", 610], ["7/1/2011", 720], ["8/1/2011", 500], ["9/1/2011", 500] ]
}
The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.
The fetch() method takes the URL of the JSON file as an argument and returns a Promise object. After resolving the Promise object we will get the JSON data in the Response object. We have the JSON data in data stored in a variable. Now we can use it to display the data in the webpage.
Example - Demo http://jsfiddle.net/kVdZG/
You can iterate and append the elements.
<table id='scores' border="1"></table>
JS -
var data = { "scores" : [ ["3/1/2011", 610],["4/1/2011", 610],["5/1/2011", 610],["6/1/2011", 610], ["7/1/2011", 720], ["8/1/2011", 500], ["9/1/2011", 500] ] }
$(data.scores).each(function(index, element){
$('#scores').append('<tr><td> '+element[0]+' </td> <td> '+element[1]+' </td></tr>');
})
jQuery does not provide any function to format JSON as a HTML table. jQuery provides only the functionality required to itterate the JSON object and manipulate the DOM. However, there are jQuery plugins that can do that.
https://github.com/gajus/json-to-table
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With