0

I'm trying to export JSON file data to a table but I'm not sure how to access nested elements of the JSON file.

This is my JSON:

{
"fruits color": "red",
"farmers market": "2019",
"sellers": [{
    "day": "1",
    "seller": [{
            "name": "John",
            "sales": "50",
            "types": "3",
            "type": [
                "apples",
                "strawberries",
                "rapsberries"
            ]
        },
        {
            "name": "Adam",
            "sales": "45",
            "types": "2",
            "type": [
                "cranberries",
                "redcurrants"
            ]
        }
    ]
}   
]}

I have a simple HTML form where I can select the file from a drop-down menu.

When my file is selected my JavaScript function pulls the information from it and sends it to a table:

function fruitSelection() {
var items = document.getElementById("fruit-colors");
var value = items.options[items.selectedIndex].value;
    if (value == "red") {
        JSON = "redfruits.json"
        processFruitsFile()}}

function processFruitsFile() {
  $.getJSON(JSON, function(JSONdata) {
    var JSONItems= [];

$.each(JSONdata, function(key, value) {
        JSONItems.push( "<tr" + key + "'>" + value + "</tr>");
});
    $( "<tr/>", {
        "class": "result-items",
        html: JSONItems.join("")
}).appendTo(result);});}

Now the problem I'm having is that my function works only with the first key and value pair like this: red2019[object Object]

What I'm trying to achieve is a table where I can display something like this:

Day Seller Type 1   Type 2        Type 3
1   John   apples   strawberries  raspberries

How can I access those values that are nested inside 'seller' and 'type of fruits' and format them nicely?

Thanks for help!

6
  • You want Type 1, Type 2.... in main header of table? Commented Mar 10, 2019 at 23:53
  • You need to flatten the json first, and then convert to table. There are couple of questions already on flatten'ing the object, check them out Commented Mar 10, 2019 at 23:59
  • @MaheerAli Yes, I've updated the JSON file as well to make it more clear. I would like to display the types of fruits for each vendor. The maximum is 3 types. If a vendor sells 2 types then that row would have only 2 types but 3 headers, third type under the header would be empty in that case. Commented Mar 11, 2019 at 0:03
  • 1
    I have given the answer. You said third type under the header would be empty. By this you mean that you don't want the cell be there like in answer or just want empty cell? Commented Mar 11, 2019 at 0:18
  • @Maheer Thank you! An empty cell would be great, it looks more tidy that way. Commented Mar 11, 2019 at 0:27

1 Answer 1

1

Here is way to do that using Javascript

let obj = {
"fruits color": "red",
"farmers market": "2019",
"sellers": [{
    "day": "1",
    "seller": [{
            "name": "John",
            "sales": "50",
            "types": "3",
            "types of fruits": [
                "apples",
                "strawberries",
                "rapsberries"
            ]
        },
        {
            "name": "Adam",
            "sales": "45",
            "types": "2",
            "types of fruits": [
                "cranberries",
                "redcurrants"
            ]
        }
    ]
}   
]}
function createTable(obj){
  let table = document.createElement('table'); 
  table.className = 'table';
  let thead = document.createElement('thead');
  let tbody = document.createElement('tbody');
  let noOfFriuts = 0;
  let {sellers}  = obj 
  for(let day of sellers){ 
    for(let seller of day.seller){
      let tr = document.createElement('tr');
      tr.innerHTML += `<td>${day.day}</td>`
      tr.innerHTML += `<td>${seller.name}</td>`
      for(let fruit of seller['types of fruits']){ 
        
        tr.innerHTML += `<td>${fruit}</td>`
      }
      noOfFriuts  = Math.max(noOfFriuts ,seller['types of fruits'].length);
      tbody.appendChild(tr)
    }
    
  }
  let tr = document.createElement('tr');
  tr.innerHTML = `<th>Day</th>
    <th>Name</th>`  
  for(let i = 1;i<=noOfFriuts;i++){
    let th = document.createElement('th');
    th.innerHTML = `Type ${i}`
    tr.appendChild(th)
  }
  
  thead.appendChild(tr);
  table.appendChild(thead);
  table.appendChild(tbody);
  document.body.appendChild(table);
  document.querySelectorAll('tr').forEach(tr => {
    let dif = -(tr.cells.length - noOfFriuts - 2);
    for(let i = 0;i<dif;i++) tr.innerHTML += "<td></td>"
  })
  
}
console.log('x')
createTable(obj);
table{
  padding:2px;
  border-collapse:collapse;
  border:2px solid;
}
td,th{
border:1px solid;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, I'm trying to implement your solution but I want to read the JSON data from a file instead from the JS file. I'm trying to use variable instead like so: let obj = "fruits.json" but I'm getting an error saying "sellers" is undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.