0

Hello in the code below i want to load the local JSON file instead of data manually, I wanted my code to read all the data from the file and show in the HTML table. My JSON file is placed in src/main/resources/json/movies.json. In the code instead of writing JSON array as shown as var movies= [{}]...I wanted to push a local JSON file.

<!DOCTYPE html>
<html>
<head>
    <title>Convert JSON Data to HTML Table</title>
    <style>
        th, td, p, input {
            font:14px Verdana;
        }
        table, th, td 
        {
            border: solid 1px #DDD;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body>
    <input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
    <p id="showData"></p>
</body>

<script>
    function CreateTableFromJSON() {
        var movies = [
            {   "title":"The Shawshank Redemption", 
                "imdb-id":"tt0111161", 
                "rank":"1", 
                "rating":"9.216891492644972", 
                "rating-count":"2025250"
                }
        ]

        // EXTRACT VALUE FOR HTML HEADER. 
        // ('Book ID', 'Book Name', 'Category' and 'Price')
        var col = [];
        for (var i = 0; i < movies.length; i++) {
            for (var key in movies[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }

        // CREATE DYNAMIC TABLE.
        var table = document.createElement("table");

        // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

        var tr = table.insertRow(-1);                   // TABLE ROW.

        for (var i = 0; i < col.length; i++) {
            var th = document.createElement("th");      // TABLE HEADER.
            th.innerHTML = col[i];
            tr.appendChild(th);
        }

        // ADD JSON DATA TO THE TABLE AS ROWS.
        for (var i = 0; i < movies.length; i++) {

            tr = table.insertRow(-1);

            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = movies[i][col[j]];
            }
        }

        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
        var divContainer = document.getElementById("showData");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);
    }
</script>
</html>
  • Use AJAX to grab the file data and load it into the `movies` object like so: https://stackoverflow.com/questions/14388452/how-do-i-load-a-json-object-from-a-file-with-ajax – Bitz Nov 05 '19 at 19:20
  • 1
    Please clarify what you mean by "local". In my mind, that means local to the web browser or client and not on the server. If it's on the server, you need to perform an HTTP GET to read the JSON data into JavaScript and then you can build an HTML Table from that data. If you mean a local file, like on the Users computer, then it has to be accessed via File input. – Twisty Nov 05 '19 at 21:46

2 Answers2

0

Assuming that src/main/resources/json/movies.json is a Server Side document, the following example should help you:

var testData = [{
  "title": "The Shawshank Redemption",
  "imdb-id": "tt0111161",
  "rank": "1",
  "rating": "9.216891492644972",
  "rating-count": "2025250"
}];

$(function() {
  function createTableFromJSON(jData) {
    // Find Column Headers
    var col = [];
    $.each(jData[0], function(key, val) {
      col.push(key);
    });

    // Create Table via jQuery Object
    var table = $("<table>", {
      class: "data-table"
    });

    // Append Header Row
    table.append($("<tr>", {
      class: "data-table-header-row"
    }));

    // Populate Header Cells
    $.each(col, function(k, h) {
      var th = $("<th>").html(h).appendTo($("tr:eq(0)", table));
    });

    // Append new Rows and Populate Cells
    $.each(jData, function(i, r) {
      var tr = $("<tr>", {
        class: "data-table-row"
      }).appendTo(table);
      $.each(r, function(j, c) {
        $("<td>").html(c).appendTo(tr);
      });
    });

    // Return Table jQuery Object
    return table;
  }

  // Bind Click Callback to Button
  $("#create-table").click(function() {
    /*
    $.getJSON('./src/main/resources/json/movies.json', function(response){
      $("#showData").html(createTableFromJSON(response));
    });
    */
    $("#showData").html(createTableFromJSON(testData));
  });
});
th,
td,
p,
input {
  font: 14px Verdana;
}

table,
th,
td {
  border: solid 1px #DDD;
  border-collapse: collapse;
  padding: 2px 3px;
  text-align: center;
}

th {
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="create-table" type="button" value="Create Table From JSON" />
<p id="showData"></p>

I used testData for testing. In the comments, you will see:

$.getJSON('./src/main/resources/json/movies.json', function(response){
  $("#showData").html(createTableFromJSON(response));
});

This will GET the JSON data and read the JSON into the variable response. You can feed that direct into your function and push it to the document via .html().

Twisty
  • 30,304
  • 2
  • 26
  • 45
-1

Check the post it has some important information to achieve what you want. At a high level, modern browsers do not let you access local files without user intervention, so you cannot include a json file in the html tags. Yes you can include javascript files but not files with extension json. Now coming to the original ask, there are various ways in which you can set up a json file on a server and then you can get the JSON file using ajax GET call. Like you can host the file on many places in the internet-

  1. http://myjson.com
  2. https://jsonbin.io/
  3. github pages
kode_anil
  • 66
  • 1
  • 6