How do I write a js that extract some selected contents from a json file to display on a local webview as a function of another app. But it seems like every method to parse the json that I got from Google didn’t work.
My current html declaration:
<html>
<body onload="onLoad()" scroll="no">
</body>
<script src="main.js"></script>
</html>
main.js:
var JSON_FILE = "data.json";
function loadData {
const fs = require('fs');
var allStrings;
fs.readFile(JSON_FILE, 'utf8', (err, data) => {
if (err) {
console.log("Error reading file from disk");
} else {
// parse JSON string to JSON object
allStrings = JSON.parse(fs.ReadFileSync(JSON_FILE));
}
})
}
function onLoad {
loadData();
};
onLoad();
and it got this error: Uncaught ReferenceError: require is not defined
I tried to add "type="module"" to script declaration but it got this error:
Access to script at 'file:///C:/project/xxxxxx/html_document/main.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome-untrusted, https, edge.
And: "Uncaught ReferenceError: onLoad is not defined"
I also tried this but it also didn’t work:
var allString = JSON.parse(ReadFileSync(JSON_FILE));
got this error Uncaught ReferenceError: ReadFileSync is not defined
2
Answers
So it seems that it can't be done a web browser since reading files or fetch requires addition lib or JSNode which can't be done for a simple website.
But I found a workaround solution by instead of reading from a json file, I declare the json string in a separated js file:
Probably not the best approach but it satisfied my requirement for a light, simple website.
try the below code in main.js
// No need to call onLoad here since it’s already being called on body load