skip to Main Content

I have

/mysite/index.html

Then I have a folder /mysite/products/ with JSON files as following:

/mysite/products/1.json
/mysite/products/2.json
/mysite/products/3.json
   ...
/mysite/products/578.json

and etc…

Every JSON file looks like this:
[{"id":1,"name":"16' Tire Japan","stock":145}]

In my HTML I have a table:

<table>
   <thead>
      <th>id</th>
      <th>name</th>
      <th>stock</th>
   </thead>
   <tbody id="products"></tbody>
</table>

Then I have a file /mysite/script.html connected with my HTML.

How can I fetch all existing .JSON files one by one from my /products folder into the table tbody (id=products) using JavaScript?

Now I have one JSON file for all products and I use fetch() like this:

fetch("products.json")
  .then(function(response) {
    return response.json();
    })
  .then(function(products){
    let placeholder = document.querySelector("#products");
    let out = "";
    for(let product of products){
        out += `<tr id='tr${product.id}'>
                <td class='id'>${product.id}</td>
                <td class='name'>${product.name}</td>
                <td class='stock'>${product.stock}</td>
            </tr>`;
    }
    placeholder.innerHTML = out;
  });

2

Answers


  1. First of all you need to store somewhere information about all your "/mysite/products/*.json" files.

    A. You can hardcode it in your script

    const filePaths = [];
    for (let i = 1; i <= 578; i++) {
     filePaths.push(`http://your.web.site/mysite/products/${i}.json`);
    }
    

    B. ..or you can download it remotely.

    const filePaths = fetch('http://your.web.site/mysite/products/index.json')
        .then((response) => response.json())
    

    Then you can download all your files:
    A. One by One

    const array_of_products = []
    filePaths.forEach(item => {
    fetch(item)
      .then(response => response.json())
      .then(data => {
        array_of_products = array_of_products.concat(data)
      })
    });
    

    B. … or you can do that simultaneously with Promise.all(array_of_fetch)

    try { 
        const responses = await Promise.all(filePaths.map(url => 
    fetch(url))); 
        const jsonPromises = responses.map(response => response.json()); 
        const data = await Promise.all(jsonPromises); 
    
        const combinedData = data.reduce((acc, item) => ({ ...acc, ...item }), {}); 
        console.log(combinedData); 
    } catch (error) { console.error('Error:', error); }
    

    Then you can do your part of code "let placeholder = …" to populate your table

    Pleaes note that many browser has only 6-12 allowed connections and it can take quite long time to download 578 files.

    Good luck with your project =)

    Login or Signup to reply.
  2. maybe something like this

    see also for await…of doc

    async function loadProducts()
      {
      const
        urlFiles  = ArrayFrom({length:578},(_,i)=>`products/${i+1}.json`)
      , tableBody = document.querySelector('#products')
        ;
      for await (const urlFile of urlFiles)
        {
        const resp     = await fetch(`products/${i}.json`);
        const products = await resp.json();
        for(const product of products)
          {
          let row = tableBody.insertRow();
          row.id  = `tr${product.id}`;
          row.insertCell().textContent = product.id;
          row.insertCell().textContent = product.name;
          row.insertCell().textContent = product.stock;
          })
        }
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search