How do I import data from JSON to JavaScript?

I’m basically trying to populate a website with data taken from a JSON file and sorted out in JavaScript.

Currently, the method I used was

import JOBS from "./database/career.json" assert {type: "json"};
console.log(JOBS);

Unfortunately, when I tested it on my browser, I got this error message on the console.

Uncaught SyntaxError: import assertions are not currently supported

Any idea what the problem is?

Looks like you can’t use that feature in your browser.

You likely need to use fetch. Just keep in mind that it’s asynchronous.

fetch("./database/career.json")
  .then((res) => res.json())
  .then((data) => {
    // do stuff with the data
  });

What type of bundler are you using? I import json files all the time, no need to “assert”, it just imports the json file as a JS object.

Okay, I took away the “assert”. Unfortunately, I then got this error in the console.

Loading module from “http://127.0.0.1:3000/js/database/career.json” was blocked because of a disallowed MIME type (“application/json”). 127.0.0.1:3000
Loading failed for the module with source “http://127.0.0.1:3000/js/database/career.json”. 127.0.0.1:3000:11:1

Probably no bundler, this is on the proposals track to be able to import JSON directly in the browser.

Basically, as of now, you can only import .js files. So, either change your .json file to a .js file and add export default to the beginning, or use fetch as I showed above.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.