Home > Software engineering >  TypeError: 'application/json' is not a valid JavaScript MIME type
TypeError: 'application/json' is not a valid JavaScript MIME type

Time:09-08

I am trying to import a JSON file into a JavaScript with the following statement

import phone_numbers from "./phoneNumbers.json";

The JavaScript file is loaded as a module into my HTML file like this

<script type="module" src="./scripts/main.js"></script>

When I view The page, I get the following error

TypeError: 'application/json' is not a valid JavaScript MIME type.

I have tried importing it like this

import phone_numbers from "./phoneNumbers.json" assert { type: "json" };

but I get the following error then

SyntaxError: Unexpected identifier 'assert'. Expected a ';' following a targeted import declaration.

How can I import a json file into a JavaScript file correctly

Thanks in advance

CodePudding user response:

There are four basic options.

Use Node.js and CommonJS

const phone_numbers = require("./phoneNumbers.json");

Since you are working with a browser, this isn't an option for you.

Use JSON modules

You'll need something that supports the proposed JSON module specification such as Node.js and the correct syntax:

import phone_numbers from "./phoneNumbers.json" assert { type: 'json' };

Preprocess the JSON

Tools like Webpack can process an import ... .json' statement and bundle the JSON into an app.

Use Ajax instead

const response = await fetch("/url/to/phoneNumbers.json");
const phone_numbers = await response.json();

You'll need to use something that supports top-level await or move the code inside an async function.

CodePudding user response:

You cannot just import a JSON file as JS, but instead have to load it from the server manually with your JS code - using something like XMLHttpRequest or the newer fetch-API.

Many web frameworks have specialized HTTP clients included for that, using framework features - so if you use a framework, look at what they give you.

  • Related