简体   繁体   中英

How can i get an array of JSON object from a webpage and add each element to the row in HTML?

I have a webpage which contains an array of JSON objects like this :

[ 
  {
 id: 10  
name : abc
  },
  {
 id: 11  
name : xyz
  }
]

I want these elements to be added to an HTML table so that the table looks like this: 在此输入图像描述

 //<[!CDATA[ /* external.js */ var doc, bod, M, I, Q, S, tableize, old = onload; // for use on other pages onload = function(){ if(old)old(); // change old var name if using technique on other pages doc = document; bod = doc.body; M = function(tag){ return doc.createElement(tag); } I = function(id){ return doc.getElementById(id); } Q = function(selector, withinElement){ var w = withinElement || doc; return w.querySelectorAll(selector); } S = function(selector, withinElement){ var w = withinElement || doc; return w.querySelector(selector); } tableize = function(tableArray){ for(var i=0,tbd=I('tbd'),l=tableArray.length; i<l; i++){ var o = tableArray[i], tr = M('tr'), id = M('td'), nm = M('td'); id.innerHTML = o.id; nm.innerHTML = o.name; tr.appendChild(id); tr.appendChild(nm); tbd.appendChild(tr); } } var tableArray = [ {id:10, name:'abc'}, {id:11, name:'xyz'} ]; tableize(tableArray); } //]]> 
 /* external.css */ html,body{ padding:0; margin:0; } body{ background:#000; overflow-y:scroll; } .main{ width:940px; background:#ccc; padding:20px; margin:0 auto; } table{ border-collapse:collapse; font:20px Arial, Helvetica, sans-serif; text-align:center; } thead{ background:yellow; } th,td{ padding:0 20px; } 
 <!DOCTYPE html> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> <head> <meta http-equiv='content-type' content='text/html;charset=utf-8' /> <meta name='viewport' content='width=device-width' /> <title>Test Template</title> <link type='text/css' rel='stylesheet' href='external.css' /> <script type='text/javascript' src='external.js'></script> </head> <body> <div class='main'> <table id='table'> <thead><tr><th>ID</th><th>Name</th></tr></thead> <tbody id='tbd'></tbody> </table> </div> </div> </body> </html> 

What you want is simple parsing of the JSON object. Check the link from w3schools which is pretty basic.

https://www.w3schools.com/js/js_json_parse.asp

Since you tagged this question as Javascript I will assume this will be done using it.

Using the examples from w3 and what you provided:

[{ 'id': '10', 'name' : 'abc' } ,{ 'id': '11', 'name' : 'xyz' }]

The whole code would run as simple as this

<!DOCTYPE html>
<html>
  <body>
    <h2>Create Table from JSON String</h2>
    <table id="demo"></table>
    <script>
      var string = '[{"id": 10, "name": "abc"}, {"id": 11,"name": "xyz"}]';
      var rows = '';
      var jsonData = JSON.parse(string);

      for (var i = 0; i < jsonData.length; i++) {
        var obj = jsonData[i];
        rows += "<tr><td>" + obj.id +"</td><td>" + obj.name +"</td></tr>"
      }
      document.getElementById("demo").innerHTML = "<tr><th>Id</th><th>Name</th></tr>" + rows;
    </script>
  </body>
</html>

I see there are some answers already, but I just wanted to make you see how easy this could be.

From the looks of it, in order to parse those JSON objects, you will need to either; correct the formatting at the source, or normalize the JSON data on your end prior to processing the data for your table.

When you say you are getting it from a URL, is the data Url-Encoded?

?data=%7B%22name%3A%22ABC%22,%22id%22%3A%221%22%7D

Or are you getting this data as a response from a request?

You are going to want to make sure you are working with valid JSON.

[{"id": 10, "name" : "abc" }, { "id": 11,  "name" : "xyz"}]

Once you are working with valid data, I'm certain one or all of the below examples should work for you.

Remember, if you are working with a string of JSON data, parse it first:

JSON.parse(data);

If you need the data as a string

JSON.stringify(data)

How about:

  1. Empty table
  2. Make GET request
  3. Foreach loop the results
  4. Populate Table Header, Body and Foot

 // CLICK EVENT $( "#btn_ajax_get_all" ).on('click', function() { // Call function ajaxGetAll(); console.log('Works up to here.'); }); function ajaxGetAll() { $.get( "php_pdo_mysql_select_all.php", function( data ) { console.log('ajaxGetAll() function called.'); console.log('[' + data.length + '] records found.'); // A. Empty table $('#table1').empty(); // B. Add thead tag to table $('#table1').append('<thead>'); // C. Add tr tag to thead $('#table1 > thead').append('<tr>'); // D. Add th tags to tr inside thead $('#table1 > thead > tr:first').append( $('<th data-type=\\"string\\">').text('id'), $('<th data-type=\\"string\\">').text('name') ); $('#table1').append('<tbody>'); // E. Run our JSON data returned, through a JQuery for each loop.... $.each(data, function(row_idx, row) { // Now we can access properties using dot notation. // *Properties names are case sensitive! Make sure // your database field names match the case after the . exactly. // Create an html <tr> element for each JSON array item... var $tr = $('<tr>').append( // ..and fill it with specific row.column_name of our choice. $('<td>').text(row.id), $('<td>').text(row.name) ); // Append each generated html <tr> element to table1 $tr.appendTo($('#table1 > tbody')); }); // END for each loop // F. Add tfoot tag to table $('#table1').append('<tfoot>'); // G. Add tr tag to tfoot $('#table1 > tfoot').append('<tr>'); // H. Add th tags to tr inside tfoot $('#table1 > tfoot > tr:first').append( $('<th>').text('something_else_1'), $('<th>').text('something_else_2') ); console.log('4.5 Table table1* populated with [' + data.length + '] records found.'); }, 'json' ); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="table1" border="1"> <thead> <tr> <th>id</th> <th>name</th> </tr> </thead> <tfoot> <tr> <th>-</th> <th>-</th> <tr> </tfoot> <tbody> <tr> <td>10</td> <td>abc</td> </tr> <tr> <tr> <td>11</td> <td>xyz</td> </tr> </tbody> </table> <p> <button type="button" id="btn_ajax_get_all">Populate Table</button> 

Solution using jQuery

One thing worth to mention about the JSON string is that the members need to be separated by a comma. Also strings need to be between " or ' as specified in https://www.json.org/

json.html

[ 
  {
   "id": 10,  
   "name" : "abc"
  },
  {
   "id": 11,
   "name" : "xyz"
  }
]

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>My Page</title>
</head>
<body>
  <table id='data'>
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>

 <!-- jQuery CDN -->
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <script src="script.js"></script>
</body>
</html>

You can make an AJAX request using the $.ajax() method and set it to convert the response to a Javascript object . Then you can create and add one row to the table for each member in the JSON using the $.each() method.

script.js - See about the ajax method's settings in jQuery documentation .

$(document).ready( function() {
  $.ajax({
    url: "json.html",
    method: "GET",
    dataType: "json",
    success: function(data) {
       var $tbody = $("table#data tbody");   // DOM cache

       $.each(data, function(i, obj) {  // parsing the array

          var $tr = $("<tr></tr>");     // Creates a row
          $tr.appendTo($tbody);         // Appends to the table

          var $td = $("<td></td>");  // Creates a cell
          $td.html(obj.id)           // Insert the data
             .appendTo($tr);         // Appends to the row
          $td = $("<td></td>");      // Creates another cell
          $td.html(obj.name)         // Insert the data
             .appendTo($tr);         // Appends to the row
       });
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("AJAX ERROR",textStatus,errorThrown,jqXHR);
    }
  });
});

I tried to keep it simple for better understanding but since the JSON is structured as an array of objects, you can have a nested $.each() inside the first $.each() so you can read the values of each member of each object independently.

Any questions you can ask.

Use this service ( http://json2table.com ) to get the html table from your json. And be careful to have valid json string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM