Skip to content

Import JSON from a local file and assign to variable in JavaScript

We can use require statements to import a JSON from a file to a variable.

const data = require('../mock/responses.json');
console.log(data);
Advertisements

Another way is to use fetch().

fetch("../mock/responses.json")
.then(mockResponses => {
   return mockResponses.json();
})
.then(data => console.log(data));
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.