Convert JSON array to an HTML table in jQuery
I'm not sure if is this that you want but there is jqGrid. It can receive JSON and make a grid.
convert json to html table using jquery
Assuming you have a well-formatted JSON file, you can do It like this:
$(document).ready(function() { // $.getJSON(url, callback); $.getJSON('https://api.myjson.com/bins/aruak', function(json) { tableGenerator('#tableName', json); });});
function tableGenerator(selector, data) { // data is an array var keys = Object.keys(Object.assign({}, ...data));// Get the keys to make the header // Add header var head = '<thead><tr>'; keys.forEach(function(key) { head += '<th>'+key+'</th>'; }); $(selector).append(head+'</tr></thead>'); // Add body var body = '<tbody>'; data.forEach(function(obj) { // For each row var row = '<tr>'; keys.forEach(function(key) { // For each column row += '<td>'; if (obj.hasOwnProperty(key)) { // If the obj doesnt has a certain key, add a blank space. row += obj[key]; } row += '</td>'; }); body += row+'<tr>'; }) $(selector).append(body+'</tbody>');}
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script><table id="tableName"></table>
Convert JSON array to html table onchange of dropdown list
You can use filter
like so:
$(document).ready(function() { var json = [{ "Model": "BMW", "Car_Model": "6-series Gran Turismo", "Year": "2018", "Color": "Orange", "Price": "$71,195" }, { "Model": "BMW", "Car_Model": "i8", "Year": "2019", "Color": "Black", "Price": "$148,495" }, { "Model": "BMW", "Car_Model": "M5", "Year": "2017", "Color": "Blue", "Price": "$103,595" }, { "Model": "Toyota", "Car_Model": "Sedan", "Year": "2017", "Color": "White", "Price": "$102,510" }, { "Model": "Toyota", "Car_Model": "Camry", "Year": "2015", "Color": "Red", "Price": "$122,810" }, { "Model": "Toyota", "Car_Model": "Corolla", "Year": "2016", "Color": "Blue", "Price": "$152,870" }, { "Model": "Toyota", "Car_Model": "Hilux", "Year": "2018", "Color": "Black", "Price": "$258,695" }, { "Model": "Toyota", "Car_Model": "Vios", "Year": "2019", "Color": "Blue", "Price": "$198,615" }, { "Model": "Hyundai", "Car_Model": "Elantra", "Year": "2017", "Color": "Black", "Price": "$152,590" }, { "Model": "Hyundai", "Car_Model": "Tucson", "Year": "2018", "Color": "Red", "Price": "$132,690" }, { "Model": "Honda", "Car_Model": "Civic", "Year": "2016", "Color": "Blue", "Price": "$171,395" }, { "Model": "Honda", "Car_Model": "Accord", "Year": "2019", "Color": "Black", "Price": "$159,445" }, { "Model": "Honda", "Car_Model": "CR-V", "Year": "2017", "Color": "White", "Price": "$193,675" } ];
$("#MODEL").on("change", () => { $("table").html(`<tr><th>Model</th><th>Car Model</th><th>Year</th><th>Color</th><th>Price</th></tr>`); var matchJSON = json.filter(e => e["Model"].toLowerCase() == $("#MODEL").val().toLowerCase()); matchJSON.forEach(obj => $("table").append(`<tr><td>${obj["Model"]}</td><td>${obj["Car_Model"]}</td><td>${obj["Year"]}</td><td>${obj["Color"]}</td><td>${obj["Price"]}</td></tr>`)); });});
th,td { padding: 28px; font-weight: normal; text-align: center; border: 1px solid black;}
th { font-weight: bold;}
<!DOCTYPE html><html>
<head>
<meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script></head>
<body> <form action="" method="POST"> <tr> <td><b>MODEL: </b></td> <td> <select id="MODEL" NAME="MODEL" size="1" required> <option value="" selected="selected">Select Model...</option> <option value="BMW"> BMW </option> <option value="TOYOTA"> Toyota </option> <option value="HYUNDAI"> Hyundai </option> <option value="HONDA"> Honda </option> </select> </td> </tr> <HR /> <table> <tr> <th>Model</th> <th>Car Model</th> <th>Year</th> <th>Color</th> <th>Price</th>
</tr> </table> </form></body>
</html>
Convert a HTML table data into a JSON object in jQuery
An HTML table? Like, all the <td>
contents in a 2-d array?
var tbl = $('table#whatever tr').map(function() {
return $(this).find('td').map(function() {
return $(this).html();
}).get();
}).get();
Then just use $.json (or whatever library you want) to turn that into a JSON string.
edit — re-written to use the native (shim here) .map()
from the array prototype:
var tbl = $('table#whatever tr').get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
The jQuery .map()
function has the "feature" of flattening returned arrays into the result array. That is, if the callback function returns a value that is itself an array, then instead of that returned array becoming the value of one cell of the .map()
result, its elements are each added to the result.
It might work to use the original jQuery version and just wrap an extra array around the returned values.
How to extract data from json array with jquery and append it in html table?
You need to loop through data.hotelMitem
, not data
itself. As the keys are static you can just access them directly without the additional inner loop. You then need to build the actual HTML to populate the table with tr
and td
elements. You can achieve that using map()
, like this:
var data = { hotelMitem: [{ hname: "idly", iprice: "5" }, { hname: "dosa", iprice: "20" }, { hname: "dosa", iprice: "20" } // more items... ]};
var html = data.hotelMitem.map(function(obj) { return `<tr><td>${obj.hname}</td><td>${obj.iprice}</td></tr>`;});$("#datatable").append(html)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><table id="datatable"></table>
Html table to array of json
Basic Solution - Demo
Because you are using actual input fields, all you really need to do is wrap it in a form. Once you have it as a form, you can select it using jQuery and call serializeArray()
to create a name-value array of your inputs.
var table = $('#my_form').serializeArray();
console.log(table);
alert(JSON.stringify(table));
The result isn't going to be 100% like you want it. As you can see, all the inputs are in order, but there isn't a really reliable way to know the difference between the rows. Also, I don't think order is guaranteed.
[{"name":"id[]","value":"1"},
{"name":"name[]","value":"Billy"},
{"name":"col4[]","value":"Home"},
{"name":"col3[]","value":"Phone"},
{"name":"id[]","value":"2"},
{"name":"name[]","value":"Bob"},
{"name":"col4[]","value":"work"},
{"name":"col3[]","value":"Cell"}]
Maintain row groupings - Demo
If you edit your <input name="something[]">
named arrays to have the row number, then you'll be able to know which values belong together. For example, if you had two rows, the input names would look like this:
<tr class="prototype">
<td><input type="text" name="id[0]" value="1" class="id" /></td>
<td><input type="text" name="name[0]" value="Billy" /></td>
<td><input type="text" name="col4[0]" value="Home" /></td>
<td><input type="text" name="col3[0]" value="Phone" /></td>
</tr>
<tr class="prototype">
<td><input type="text" name="id[1]" value="2" class="id" /></td>
<td><input type="text" name="name[1]" value="Bob" /></td>
<td><input type="text" name="col4[1]" value="work" /></td>
<td><input type="text" name="col3[1]" value="Cell" /></td>
</tr>
(notice the name arrays have the row number in it) and the returning results would looks like this:
[{"name":"id[0]","value":"1"},
{"name":"name[0]","value":"Billy"},
{"name":"col4[0]","value":"Home"},
{"name":"col3[0]","value":"Phone"},
{"name":"id[1]","value":"2"},
{"name":"name[1]","value":"Bob"},
{"name":"col4[1]","value":"work"},
{"name":"col3[1]","value":"Cell"}]
Massage results into desired output - Demo
Obviously the results still don't match what you are looking for, but that can be fixed too. We know the name of the field, we know the field's value, and now we know its row number too. Using some regular expressions, we can separate out the name from the row number. Using a loop we can move things around to a format that we like:
var table = $('#my_form').serializeArray();
var final_results = [];
var row_patt = /\[(\d+)\]$/; // Gets the row number inside []
var name_patt = /^[^\[]+/; // Gets the name without the [0]
$(table).each( function(index, ele){
// Get the name of input and row number
var rowNum = parseInt(row_patt.exec(ele.name)[1]);
var name = name_patt.exec(ele.name);
// Add the name and value to the correct spot in results
if( final_results[rowNum] === undefined ){
final_results[rowNum] = {};
}
final_results[rowNum][name] = ele.value;
});
Now we have a nicely formatted array of hashes that list each value per row:
[{"id":"1","name":"Billy","col4":"Home","col3":"Phone"},
{"id":"2","name":"Bob", "col4":"work","col3":"Cell"}]
Failing to display json array in html table
var obj = [{ "fullname": "Frank Robsinga", "gender": "Male", "email": "n\/a", "phone": "n\/a", "status": "1"}]
for (var i = 0; i < obj.length; i++) { console.log(obj[i].fullname) console.log(obj[i].gender) console.log(obj[i].email) console.log(obj[i].phone) console.log(obj[i].status)}
<table id='usersdata'></table>
Related Topics
Invariant Violation: Objects Are Not Valid as a React Child
JavaScript Regex Multiline Text Between Two Tags
What Is the Meaning of "$" Sign in JavaScript
Empty Arrays Seem to Equal True and False at the Same Time
Object Property Name as Number
Constructors in JavaScript Objects
Promise.All Consumes All My Ram
How to Pass Data from a Page to Another Page Using React Router
How to Set the Value Property in Angularjs' Ng-Options
What Is the Meaning of the "At" (@) Prefix on Npm Packages
How to Check File Input Size with Jquery
Jquery - Setting the Selected Value of a Select Control via Its Text Description
Concrete JavaScript Regular Expression for Accented Characters (Diacritics)
How to Read the Client's MAChine/Computer Name from the Browser