Read data from External JSON file using JavaScript

Javascript js create table from json

Demo Code : Question: I have JSON file need to generate dynamic html table from using JavaScript and column headers should not be the key .and value of column header should be In 4th column , it should be a button with function. Above code will generate table with 3 headers and header name as json key.

Create HTML Table Using JSON data in JavaScript

I am still suffering with JavaScript as I am newbie so please be patient to me and guide me step by step .. and please don’t overload the comments with links because this made me lost This is the try to bypass the CORS problem

    * < font:17px 'Segoe UI'; >table, th, td < border: solid 1px #ddd; border-collapse: collapse; padding: 2px 3px; text-align: center; >th  

Data extracted from External JSON file and converted to an HTML table

response.text()) .then(contents => createTableFromJSON(contents)) .catch(() => console.log("No Access " + url + " Response. Blocked By Browser?")) //var oXHR = new XMLHttpRequest(); // Initiate request. //oXHR.onreadystatechange = reportStatus; //oXHR.open("GET", "https://www.encodedna.com/library/sample.json", true); // get json file. //oXHR.send(); // Create an HTML table using the JSON data. function createTableFromJSON(jsonData) < var arrBirds = []; arrBirds = JSON.parse(jsonData); // Convert JSON to array. var col = []; for (var i = 0; i < arrBirds.length; i++) < for (var key in arrBirds[i]) < if (col.indexOf(key) === -1) < col.push(key); >> > // Create a dynamic table. var table = document.createElement// Create table header. var tr = table.insertRow(-1); // Table row. for (var i = 0; i < col.length; i++) < var th = document.createElement("th"); // Table header. th.innerHTML = col[i]; tr.appendChild(th); >// Add JSON to the table rows. for (var i = 0; i < arrBirds.length; i++) < tr = table.insertRow(-1); for (var j = 0; j < col.length; j++) < var tabCell = tr.insertCell(-1); tabCell.innerHTML = arrBirds[i][col[j]]; >> // Finally, add the dynamic table to a container. var divContainer = document.getElementById("showTable"); divContainer.innerHTML = ""; divContainer.appendChild(table); >;

I am getting No access .. How can I read the JSON data and then convert to HTML table?

Читайте также:  METANIT.COM

You got a couple of problems, but not with the CORS, you got the results from the request. The error came from the createTableFromJSON function.

The main problems:

  • Forgot to add («table») after createElement
  • Two unnecessary loops
  • Wrong use of the JSON to get the Name
  • More tr than needed
// Create XMLHttpRequest object. const proxyurl = "https://cors-anywhere.herokuapp.com/"; const url = "https://www.encodedna.com/library/sample.json"; fetch(proxyurl + url) .then(response => response.text()) .then(contents => createTableFromJSON(contents)) .catch((e) => console.log('error'))// Create an HTML table using the JSON data. function createTableFromJSON(jsonData) < var arrBirds = []; arrBirds = JSON.parse(jsonData); // Convert JSON to array. var col = []; for (var key in arrBirds) < if (col.indexOf(key) === -1) < col.push(key); >> // Create a dynamic table. var table = document.createElement("table") // Create table header. var tr = table.insertRow(-1); // Table row. (last position) for (var i = 0; i < col.length; i++) < var th = document.createElement("th"); // Table header. th.innerHTML = col[i]; tr.appendChild(th); >tr = table.insertRow(-1); // add new row for the names // Add JSON to the table rows. for (var i = 0; i < arrBirds.length; i++) < var tabCell = tr.insertCell(-1); tabCell.innerHTML = arrBirds[i].Name; >// Finally, add the dynamic table to a container. var divContainer = document.getElementById("showTable"); divContainer.innerHTML = ""; divContainer.appendChild(table); >;
 

Data extracted from External JSON file and converted to an HTML table

I hope this helps!

Let’s create a table using JSON and JavaScript, Let’s create a table using JSON and JavaScript · Step 1 — Create JSON · Step 2 — Insert it in JS · Step 3 — Create a HTML file · Step 4 — The fun

JSON Array to HTML Table with Javascript

Fetching API data and displaying API data inside table. · JavaScript Template Literals Duration: 5:33

Читайте также:  Manager classes in java

Display JSON data in HTML table using JavaScript

Hello everyone, in this video we are going to fetch data from a JSON file, and we are going to Duration: 4:27

JSON to HTML Table

Display JSON data in HTML table using JavaScript · Loading data into HTML Tables using Duration: 1:11

Create table form JSON

I am trying to create a table from JSON. And I think I have a problem with my link but not also. No data appears on my table. My error are :

Cannot read property ‘symbol’ of undefined ‘Uncaught TypeError: Cannot read property ‘symbol ‘ of undefined at Object. (main.js:14) at Function.each (jquery.min.js:2) at Object.success (main.js:11) at u (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at k (jquery.min.js:2) at XMLHttpRequest.’

$(document).ready(function() < $.getJSON("https://api.coindesk.com/v1/bpi/currentprice.json", function(json) < enter code here var currentprice = ''; $.each(json.bpi, function(key, value) < var USD = value.USD currentprice += ''; currentprice += '' + USD.symbol + ''; currentprice += '' + USD.description + ''; currentprice += '' + USD.rate + ''; currentprice += ''; >); $("#current_table").append(currentprice); >) >) 

Check if the value exists and set to an empty string if the value does not exist.

var currentprice = ''; $.each(json.bpi, function(key, value) < var USD = value.USD var symbol = USD.symbol || "" var description = USD.description || "" var rate = USD.rate || "" += ''; += '' + symbol + ''; += '' + description + ''; += '' + rate + ''; += ''; >); $("#current_table").append(currentprice); 

You are looping through json.bpi which will give you USD,GBP..etc so just use value.keyname to get particular values from json object .

$(document).ready(function() < $.getJSON("https://api.coindesk.com/v1/bpi/currentprice.json", function(json) < var currentprice = ''; $.each(json.bpi, function(key, value) < currentprice += ''; currentprice += '' + value.symbol + ''; currentprice += '' + value.description + ''; currentprice += '' + value.rate + ''; currentprice += ''; >); $("#current_table").append(currentprice); >) >)

How to fetch data from JSON file and display in HTML table using, 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

Generate html table from json data with different table header other than json key

need to generate dynamic html table from JSON using JavaScript and column headers should not be the JSON key .and value of column header should be

Book ID |Book name|Author name | SUBMIT |:---- |:------:| -----:|--------:| | One | Two | Three |Four:| 

In 4th column , it should be a button with onclick function.

I tried to generate table. But unable to map the JSON value to column header name other than JSON key. and how to add extra column with a button.

    th, td, p, input, h3 < font:15px 'Segoe UI'; >table, th, td < border: solid 1px #ddd; border-collapse: collapse; padding: 2px 3px; text-align: center; >th   Above code will generate table with 3 headers and header name as json key. Inside col[] ,If I give correct columns headers , then it is not mapping properly

You’re doing it almost correct, but I think the order is just wrong.

You should instead use something like:

var th = document.createElement("th") for (var i = 0; i < col.length; i++) < var tabCell = th.insertCell(-1) tabCell.innerHTML = col[i] >tr.appendChild(th) 

It’s just a rough idea to show you, I’ve not tested it myself, just used what you did and changed it up a bit.

I refactored you code a bit. I replaced the for loop with forEach() that I find more readable.

The event listener for the buttons in the table is on the that holds the table. The reason is that you dont need to assign new event listeners if the table is rendered again. The only thing you need to do is to test if it was a button that was clicked.

var submitBooks = document.getElementById('submitBooks'); var showData = document.getElementById('showData'); submitBooks.addEventListener('click', tableFromJson); showData.addEventListener('click', e => < if(e.target.nodeName == 'BUTTON')< console.log(e.target.attributes.item('data-id').value); >>); function tableFromJson() < // the json data. (you can change the values for output.) var details = [< "id": "11256310", "desc": "desc", "author": "abc", >, < "id": "33856310", "desc": "desca", "author": "abcA", >, < "id": "73856310", "desc": "descB", "author": "cBonfigadminB", >]; // Extract value from table header. var cols = ['id', 'desc', 'author', 'submit']; // Create a table. var table = document.createElement("table"); // Create table header row var tr = table.insertRow(); // table row. cols.forEach(col => < let th = document.createElement("th"); // table header. th.innerHTML = col; tr.appendChild(th); >); // add json data to the table as rows. details.forEach(detail => < let tr = table.insertRow(); Object.keys(detail).forEach(key =>< let tabCell = tr.insertCell(); tabCell.innerHTML = detailJavascript create table form json; >); let tabCell = tr.insertCell(); let button = document.createElement('BUTTON'); // create button button.textContent = 'Submit'; let dataid = document.createAttribute('data-id'); // attribute for button what holds id dataid.value = detail.id; button.attributes.setNamedItem(dataid); tabCell.append(button); >); // Now, add the newly created table with json data, to a container. var divShowData = document.getElementById('showData'); divShowData.innerHTML = ""; divShowData.appendChild(table); >
th, td, p, input, h3 < font: 15px 'Segoe UI'; >table, th, td < border: solid 1px #ddd; border-collapse: collapse; padding: 2px 3px; text-align: center; >th

Источник

Convert JSON to HTML Table using Javascript

This article shows you how can you convert JSON to HTML table using Javascript. It also shows you to display the JSON data in the Bootstrap table.

Overview

Javascript JSON is a standard key-value pair (text-based format) for representing structured data based on Javascript object syntax. It is commonly used for transferring data in web applications such as sending data from the server to the client or vice-versa.

The JSON object format is a little technical for the end user to understand, so displaying the JSON data on the web page in HTML table format is very helpful for the end user to understand.

In this article, you will learn to display JSON data in an HTML table using javascript as well as display JSON data objects in a responsive bootstrap table.

How do convert JSON to a Table?

To convert a JSON object to an HTML table, we should have some JSON. Let’s assume, we have employee records in the form of a JSON object which contains the employee information (employee name, address, email id, and age) as follow:

[ < "Employee Name":"Rahul Singh", "Address":"Hyderabad", "Email ID":"[email protected]", "Age":25 >, < "Employee Name":"Pawan Patil", "Address":"Mumbai", "Email ID":"[email protected]", "Age":27 >, < "Employee Name":"karl Jablonski", "Address":"Seattle", "Email ID":"[email protected]", "Age":25 >, < "Employee Name":"Jhon Smith", "Address":"New Yark", "Email ID":"[email protected]", "Age":22 >]

Javascript code to show JSON data in HTML

Let’s see the javascript code with a complete example to create a table from a JSON object as follow:

      

Convert JSON data to simple HTML Table



JSON to HTML Table Live Demo

convert json to html table in javascript | show json data in html

Live Demo

How to convert JSON to a bootstrap Table in javascript?

To make the table responsive, we create the bootstrap table. With the small modification in the above example, we can convert JSON to a bootstrap table example in javascript. Bootstrap has a lot of pre-defined class names for making tables responsive such as .table, .table-bordered, .table-striped, etc.

We have to import the following bootstrap CSS library into the tag of the HTML document.

[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

Create a bootstrap table from JSON data example

     [email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> Convert JSON data to Bootstrap Table  

JSON To Bootstrap Table Live Demo

Create bootstrap table from json data in javascript

Live Demo

Conclusion

In this article, you have seen displaying the JSON object data to a simple HTML table as well as a bootstrap responsive table using javascript.

If you want to display an Excel file data into a table, read another article here: Display Excel data in HTML Table using SheetJS in JavaScript.

You might like this:

Источник

Оцените статью