0

Im creating a website using a json file to store the data to be used on one of the pages, but I am struggling to import the data successfully. Im using repl.it to code in.

So far I've tried:

var data = require("data.json") and got ReferenceError: require is not defined

and

<script src="data.json"></script> const dta = JSON.parse(data) and got ReferenceError: data is not defined

And Ive looked at other questions and been really confused by them

Im not sure whether this is related but I also get a syntax error in my json file set out like data = '[{"foo": "bar"}]'

How can i fix these errors?

1 Answers1

1

require is a Node.js function. It (at the time of writing) does not exist in browsers just yet. And you never did declare data so yes it's not defined. You can fetch the JSON data using the Fetch API:

fetch('/data.json').then((res) => res.json()).then((data) => console.log(data))

Search up "promises" on MDN for info about the thenmethod To be able to access data globally, you can use an Immediately Invoked Function Expression (IIFE) with async/await.

(async function() {
const data = await fetch('/data.json').then((res) => res.json()).then((data) => data);
})();

Search up "IIFE" on MDN for more info, and async/await is a way to consume promises.

  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/224451/discussion-on-answer-by-expressjs123-use-javascript-to-import-a-json-file). – Samuel Liew Nov 12 '20 at 01:44