Home > Blockchain >  How to display data from local JSON file to HTML table?
How to display data from local JSON file to HTML table?

Time:06-30

I have a local JSON file prices.json that looks like this:

{
  "Company01": {
    "price": "R$600,50",
    "price2": "R$700,40"
  },
  "Company02": {
    "price": "R$800,45",
    "price2": "R$500,22"  
}

I need to display those prices on a table, on my index.html. The HTML code looks like this:

<table id="prices-table">
                <tr>
                  <th >★</th>
                  <th >PRICE 1</th>                  
                  <th >PRICE 2</th>
                </tr>
                <tr>
                  <td>Company 1</td>
                  <td></td>                  
                  <td></td>
                </tr>
                <tr>
                  <td>Company 2</td>
                  <td></td>                  
                  <td></td>
                </tr>
</table>

I'm not sure how to do it either with JS or Jquery (Which, i guess, would be preferable)

CodePudding user response:

In modern vanilla JS with comments...

The functions below will create an entire HTML table, using the first object to populate the table heading row. In this way, it assumes that all objects will have the same keys. Once created, the table is appended to the DOM.

The names of the object properties do not need to be known with this approach, and it will support an open-ended number of table rows.

// fetch JSON - Returns a JS object
async function getPrices () {
    const http = await fetch("prices.json");
    const response = await http.json();
    return response;
};

// read JSON into var
const prices = await getPrices();

// create table - Returns table as DOM object
function createTable() {

    // create table element
    const table = document.createElement("table");
    
    // create the thead element and first row of table headers
    const tableHead = (() => {

        // create table head
        const thead = document.createElement("thead");

        // create header row from properties of first object
        const headerRow = (() => {
            
            // create the <tr> element
            const row = document.createElement("tr");
            
            // iterate through outer object properties
            for (const property in prices) {
                
                // simplify object notation by assigning named variable
                const nestedObj = prices[property];
        
                // iterate through inner object properties
                for (const key in nestedObj) {
                    
                    // simplify object notation by assigning named variable
                    const val = nestedObj[key];

                    // create <th> element
                    const th = document.createElement("th");

                    // set a scope attribute on <th> for better A11Y
                    th.setAttribute("scope", "col");
                    
                    // add text from object keys to <th> element
                    th.innerText = key;

                    // append <th> to <tr>
                    row.appendChild(th)
                    
                }

                // prevent subsequent iterations after the first
                break;
            }

            return row;
            
        })();

        // add the <tr> element to the <thead> element
        thead.appendChild(headerRow);

        return thead;

    })();
    

    // create <tbody> populated with rows
    const tableBody = (() => {
    
        // create <tbody> element
        const tbody = document.createElement("tbody");

        // iterate through outer object properties
        for (const property in prices) {
            
            // simplify object notation by assigning named variable
            const nestedObj = prices[property];

            // create <tr> element for each body row
            const row = document.createElement("tr");
    
            // iterate through inner object properties
            for (const key in nestedObj) {
                
                // simplify object notation by assigning named variable
                const val = nestedObj[key];

                // create <td> element
                const td = document.createElement("td");

                // add the object value to the <td> element
                td.innerText = val;

                // append the <td> element to the <tr>
                row.appendChild(td)
                
            }

            // append each row to the <tbody>
            tbody.appendChild(row)

        }

        return tbody;

    })();

    // append <thead> to <table>
    table.appendChild(tableHead);

    // append <tbody> to <table>
    table.appendChild(tableBody);

    return table
}

// add table to DOM - Returns nothing 
function drawTable() {

    // get the table
    const table = createTable();

    // specify output location
    const destination = document.getElementById("table-wrapper");

    // ouput to DOM
    destination.appendChild(table);
}


drawTable();

It's worth nothing that this task is heavily complicated by the structure of the JSON (which is missing a closing brace in the example). Had it been an array of objects, this would have been a much simpler solution.

Given that this script uses async functions, you'll need to load it using <script type="module">.

CodePudding user response:

Use <thead> and <tbody> in your table. PS: <tbody> will be created by the browser anyways, so if you create it it's easier to remove and add data rows without having to tackle with static table headings titles.

<table id="prices-table">
  <thead>
    <tr>
      <th>★</th>
      <th>PRICE 1</th>
      <th>PRICE 2</th>
      </tr>
    </thead>
  <tbody></tbody>
 </table>

You don't need jQuery.
Create some simple reusable functions to query the DOM and for the enter image description here

CodePudding user response:

First parse the JSON into a javascript object:

const newObject = JSON.parse('{
  "Company01": {
    "price": "R$600,50",
    "price2": "R$700,40"
  },
  "Company02": {
    "price": "R$800,45",
    "price2": "R$500,22"  
}')

Then insert via class or id selector:

$( ".exampleClass" ).append( "<p>" newObject.Compnay01.price "</p>" );

if you get some string issue you might need to do this:

$( ".exampleClass" ).append( "<p>" " newObject.Compnay01.price " "</p>" );
  • Related