0

I'm just trying to generate a table using info from a JSON file but it is not working - I am new to HTML so I can't see what I am doing wrong. The JSON file called food.json is just like:

[
{
      "Type": "Snack",
      "Flavour": "Salted",
      "Brand": "Walkers"
   },
   {
      "Type": "Dessert",
      "Flavour": "Chocolate",
      "Brand": "Alpro",
   }
]

I have a javascript file called test.js with the following:

    $(document).ready(function () {

        $.getJSON("food.json",
            function (data) {
                var food = '';

                $.each(data, function (key, value) {

                    food += '<tr>';
                    food += '<td>' +
                        value.Type + '</td>';

                    food += '<td>' +
                        value.Flavour + '</td>';

                    food += '<td>' +
                        value.Brand + '</td>';

                    food += += '</tr>';
                });

                $('#table').append(food);
            });
    });

And below is my HTML:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <script type="text/javascript" src="jquery-3.5.1.js"></script>
        <script src="test.js"></script>
        <title>Fave Food</title>
    </head>
    <body>
        <h1>My Fave Food</h1>
        <form>
            <button onclick="getJSON()">Click for My Fave Food!</button>
        </form>
        <table id="table">
            <thead>
            <tr>
                <th>Type</th>
                <th>Flavour</th>
                <th>Brand</th>
            </tr>
            </thead>
        </table>
    </body>
    </html>
aidakemind
  • 33
  • 6
  • Does this answer your question? [Convert json data to a html table](https://stackoverflow.com/questions/5180382/convert-json-data-to-a-html-table) – Liam Feb 26 '21 at 13:58
  • your table tag is missing `id="table"` which you are using here `$('#table')` – Swati Feb 26 '21 at 14:02
  • @Liam not quite, I couldn't work out how to pass in a long JSON file as a variable? Rather than having to paste all of it into my javascript file? – aidakemind Feb 26 '21 at 14:04
  • Thanks @Swati that was actually an error when I typed up the question as I had made a few changes, have edited the question – aidakemind Feb 26 '21 at 14:10
  • are you seeing any error inside browser console ? – Swati Feb 26 '21 at 14:27
  • @Swati it is saying my function getJSON() is undefined – aidakemind Feb 26 '21 at 14:32
  • That's the problem on click, as you defined your json catch on document load, and it should load json data on page loading. Does that work ? – Ultrazz008 Feb 26 '21 at 14:36

3 Answers3

2

Unfortunately I cannot connect to the data source in this SO snippet, so I concentrated on the rest of your script first. I shortened a few bits and put them together so they would work here.

What you need to check is whether your $.parseJSON() or the replacement I used here ($.getJSON()) actually delivers the data array.

const data = [
{
      "Type": "Snack",
      "Flavour": "Salted",
      "Brand": "Walkers"
   },
   {
      "Type": "Dessert",
      "Flavour": "Chocolate",
      "Brand": "Alpro"
   }
];

$(document).ready(function () {
 // $.getJSON("food.json", function (data) {
  var food = '';
  $.each(data, function (key, value) {
    food += '<tr><td>'+value.Type+'</td>';
    food +=     '<td>'+value.Flavour+'</td>';
    food +=     '<td>'+value.Brand+'</td><tr>';
  });
  $('#table').append(food);
 // });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>My Fave Food</h1>
<form>
  <button onclick="parseJSON()">Click for My Fave Food!</button>
</form>
<table id="table">
 <thead><tr><th>Type</th><th>Flavour</th><th>Brand</th></tr></thead>
</table>

Well, the JSON part can be demonstrated with a different data source. I will use http://jsonplaceholder.typicode.com/users as it is publicly available:

$(document).ready(function () {
 $.getJSON("http://jsonplaceholder.typicode.com/users", function (data) {
  var food = '';
  $.each(data, function (key, value) {
    food += '<tr><td>'+value.name+'</td>';
    food +=     '<td>'+value.username+'</td>';
    food +=     '<td>'+value.email+'</td><tr>';
  });
  $('#table').append(food);
 });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>My Fave Users</h1>
<table id="table">
  <thead><tr><th>Name</th><th>Username</th><th>Email</th></tr></thead>
</table>
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
1

Well $.parseJSON is parsing json string, as I see you need to catch a file so you should use $.getJSON as it's shortend function to the $.ajax request.

All other should be fine.

EDIT: I have tested it, and it looks like your $.getJSON gives error instead of success, i guess your json should be formated, so when i used it like this it worked [{"Type":"Snack","Flavour":"Salted","Brand": "Walkers"},{"Type": "Dessert","Flavour":"Chocolate","Brand":"Alpro"}]

And also your button was in form, so it was refreshing every time the whole page, so i putted attribut type="button", so it doesnt trigger form submit.

Here's full working solution:

food.json

[{"Type": "Snack","Flavour": "Salted","Brand": "Walkers"},{"Type": "Dessert","Flavour": "Chocolate","Brand": "Alpro"}]

test.js

function getJSON() {
    
    $.getJSON("food.json", function (data) {
            var food = '';
            console.log( data );
            $.each(data, function (key, value) {

                food += '<tr>';
                food += '<td>' +
                    value.Type + '</td>';

                food += '<td>' +
                    value.Flavour + '</td>';

                food += '<td>' +
                    value.Brand + '</td>';

                food += '</tr>';
            });

            $('#table').append(food);
        }).done(function() {
    console.log( "second success" );
  })
  .fail(function(data) {
    console.log( "error", data );
  })
  .always(function() {
    console.log( "complete" );
  });
            
}

html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
    <script src="test.js"></script>
    <title>Fave Food</title>
</head>
<body>
    <h1>My Fave Food</h1>
    <form>
        <button type="button" onclick="getJSON();">Click for My Fave Food!</button>
    </form>
    <table id="table">
        <thead>
        <tr>
            <th>Type</th>
            <th>Flavour</th>
            <th>Brand</th>
        </tr>
        </thead>
    </table>
</body>
</html>
Ultrazz008
  • 1,678
  • 1
  • 13
  • 26
  • thank you, I have actually tried this too and it still doesn't seem to be working :( – aidakemind Feb 26 '21 at 14:20
  • Is your json file in same directory as your html file ? – Ultrazz008 Feb 26 '21 at 14:30
  • I've made working solution, and fixed some things, check it out. – Ultrazz008 Feb 26 '21 at 14:47
  • 1
    This is exactly what I have been trying to do, thank you so much. I am still getting an error but I assume this is to do with my set up so I will have a play around with it Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///Users...food.json. (Reason: CORS request not http). – aidakemind Feb 26 '21 at 14:58
0

try this (I commented form tag because of it reloads page then you lost html structure created by JS):

const data = [
  {
    Type: "Snack",
    Flavour: "Salted",
    Brand: "Walkers",
  },
  {
    Type: "Dessert",
    Flavour: "Chocolate",
    Brand: "Alpro",
  },
];

function parseJSON() {
  let food = "<tbody>";

  data.forEach((item) => {
    food += "<tr>";
    food += "<td>" + item.Type + "</td>";

    food += "<td>" + item.Flavour + "</td>";

    food += "<td>" + item.Brand + "</td>";

    food += "</tr>";
  });

  food += "</tbody>";

  let table = document.getElementById("table");
  table.insertAdjacentHTML("beforeend", food);
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <!-- <script type="text/javascript" src="jquery-3.5.1.js"></script> -->
    <script src="test.js"></script>
    <title>Fave Food</title>
  </head>
  <body>
    <h1>My Fave Food</h1>
    <!-- <form> -->
    <button onclick="parseJSON()">Click for My Fave Food!</button>
    <!-- </form> -->
    <table id="table">
      <thead>
        <tr>
          <th>Type</th>
          <th>Flavour</th>
          <th>Brand</th>
        </tr>
      </thead>
    </table>
  </body>
</html>