Please forgive me as Im not an expert in coding but Im trying to send JSON data from a file to a javascript variable on my website.
Im using NodeJS & EJS but when the variable is filled on the browser, all the " are replaced with " and an error appears.
NodeJS Server.js
// Load Node modules
var express = require('express');
const ejs = require('ejs');
const fs = require('fs');
function read(path) {
const fileContent = fs.readFileSync(path);
const array = JSON.parse(fileContent);
return array;
}
var data = read('data.txt');
data=JSON.stringify(data);
console.log(data);
// Initialise Express
var app = express();
// Render static files
app.use(express.static('public'));
// Set the view engine to ejs
app.set('view engine', 'ejs');
// Port website will run on
app.listen(8080);
// *** GET Routes - display pages ***
// Root Route
app.get('/', function (req, res) {
res.render('pages/index',{data: data});
});
html script to insert the data.
<script>
var employee= <%=(data)%>;
console.log(employee);
</script>
When I console log data in Node I get
[{"employee":{"name":"John White","idNumber":5124,"married":true}},{"employee":{"name":"Billy Brown","idNumber":3429,"married":false}}]
The information imported into the browser has replaced all the " with ".
I appreciate any help you guys could give. I've looked all day to try and find out why this is happening.
Regards.