Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery function to create table using JSON data

Tags:

json

jquery

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] ]
}
like image 571
Vonti Avatar asked Oct 18 '11 06:10

Vonti


People also ask

How do I display JSON data in HTML table using jQuery Ajax?

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.

How use fetch and display JSON data in HTML using JavaScript?

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.


2 Answers

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>');       
})
like image 135
Jayendra Avatar answered Oct 01 '22 18:10

Jayendra


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

like image 39
Gajus Avatar answered Oct 01 '22 20:10

Gajus