0

EDIT:

I just need a simple way to read the json file in the html page, can it be possible without making this complicated? I should be able to have key reference anywhere in the html page without any limitations.

END

I have html page that hosted on the heroku app and I'm trying to read the json file and display the values of json file to the html page, how would I do that?

Here is what I have tried so far.

My student JSON file:

{ 
  name: 'John Doe',
  car: 'BMW X5' 
}

My HTML page:

<html>
  <header>

    const fs = require('fs');

    let rawdata = fs.readFileSync('student.json');
    let student = JSON.parse(rawdata);
    console.log(student);
    console.log('my Name: ' + student.name);
    console.log('my Name: ' + student.car);

  </header>
  <body>
    <h1>My Name is: <%=name%> </h1>
    <p>My Car is: <%=car%></p>
  </body>
</html>
Nick Kahn
  • 19,652
  • 91
  • 275
  • 406
  • What are you seeing in the console? Are you receiving any errors? – LHM Nov 04 '19 at 20:12
  • I'm not seeing any console log in the chrome, just you know I have both the JS and html on the same page. – Nick Kahn Nov 04 '19 at 20:14
  • i updated the code. – Nick Kahn Nov 04 '19 at 20:15
  • `fs` is a NodeJS API that's not available in the browser. Use `fetch` instead to load the file, asynchronously, and then use its content. `fetch("/path-to-file.json").then(r => r.json()).then(data => { // use the parsed json data here })` – Arash Motamedi Nov 04 '19 at 20:19

2 Answers2

0

There are various ways to load a local JSON file into your web page, but only a few preferred ways to present your loaded data.

Once you load your data, it is wise to either utilize data-binding or templates to present your data.

Data-binding with knockout

// Data from load
var student = {
  name: 'John Doe',
  car: 'BMW X5'
};

var StudentViewModel = function(studentData) {
  this.name = ko.observable(studentData.name);
  this.car = ko.observable(studentData.car);
}

ko.applyBindings(new StudentViewModel(student));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<h1>My Name is: <span data-bind="text: name"></span></h1>
<p>My Car is: <span data-bind="text: car"></span></p>

Templates

// Data from load
var student = {
  name: 'John Doe',
  car: 'BMW X5'
};

window.addEventListener('DOMContentLoaded', (event) => {
  let templateHtml = document.getElementById('student-template').innerHTML;
  let StudentTemplate = Handlebars.compile(templateHtml);

  document.body.insertAdjacentHTML('beforeend', StudentTemplate(student));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.4.2/handlebars.min.js"></script>
<script id="student-template" type="text/x-handlebars-template">
  <h1>My Name is: {{name}}</span></h1>
  <p>My Car is: {{car}}</span></p>
</script>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • thank you for showing the preferred way, i have question, what is `x-handlebars-template` where the `js` code lives? – Nick Kahn Nov 04 '19 at 21:30
  • @NickKahn The script is included at the top of the HTML. It is just one of many templating libraries. – Mr. Polywhirl Nov 04 '19 at 21:32
  • in my situation i have json file that is separate how would you load that data from the file ? – Nick Kahn Nov 04 '19 at 21:44
  • hey another thing i found is that, do you have to have this ` – Nick Kahn Nov 04 '19 at 21:50
  • @NickKahn It's in the body, preferably near the end. – Mr. Polywhirl Nov 04 '19 at 21:51
  • there is so many limitations with your approach, the limitations are 1. I can not read the json file externally 2. I have to have the script tag inside the head 3. I can not read the value anywhere in the html page – Nick Kahn Nov 04 '19 at 21:53
  • just for the sake of testing I put together the way you have it above and I'm getting the error `uncaught typeerror: cannot read property `innerHTML` of null` – Nick Kahn Nov 04 '19 at 21:53
  • @NickKahn Because you are accessing the DOM content before it has loaded. You need to make sure the page has loaded. – Mr. Polywhirl Nov 04 '19 at 21:58
  • is that possible to make it simpler than this approach? I just need a way to read the file and show the values of json in anywhere in the html file, can it be possible ? – Nick Kahn Nov 04 '19 at 21:59
-2

There are 2 approaches to displaying data from a server to the client:

1) You can change your client JS code to make an http request to fetch the JSON and then dynamically update the HTML. Pro: simple, Con: additional http request.

2) Or you can edit the HTML on the server. Pro: avoids http request, Con: slightly more complex.

Server Node code:

const http = require('http');

const myJson = require('student.json', 'utf-8');
let myHtml = require('fs').readFileSync('index.html', 'utf-8');

myHtml = myHtml.replace(/<%=(\w*)%>/, (_, key) => myJson[key]);

http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(myHtml);
}).listen(8080);
junvar
  • 11,151
  • 2
  • 30
  • 46