1

I am working on a simple vanilla js project where we can't use node js and babel and I am trying to import an array from a json file and then I got this error:

Uncaught SyntaxError: Cannot use import statement outside a module

so now I want to find a way to map through the array(use .map() on it) without having to copy and paste it from the json file and put it manually in app.js

Any idea how to do that without node or webpack?

maii
  • 49
  • 6

1 Answers1

3

Node.js tends to conflate loading data from JSON and loading JavaScript modules. A number of Webpack/Babel plugins do the same thing. When you aren't using those tools you need to keep the concepts separate. import is for loading ES6 modules, not JSON data.

To load JSON, make an HTTP request to load the file with XMLHttpRequest, fetch or a library that wraps one of them. Then parse the result (with JSON.parse() or use the built-in parsing features of the API you selected).

fetch("/path/to/my.json")
    .then(response => response.json())
    .then(parsed_data => {
        const mapped_data = parsed_data.map(...);
        // etc
    });
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I tried the solution and I got this error: – maii Apr 20 '21 at 19:47
  • app.js:1 Fetch API cannot load file:///C:/Users/SUPPORT/Desktop/Javascript-master/Javascript-master/dino.json. URL scheme must be "http" or "https" for CORS request – maii Apr 20 '21 at 19:47
  • https://stackoverflow.com/questions/10752055/cross-origin-requests-are-only-supported-for-http-error-when-loading-a-local – Quentin Apr 20 '21 at 19:48