JSON module scripts are now Baseline Newly available  |  Blog  |  web.dev

0
3



Published: June 18, 2025

If you want to import a JSON file in a JavaScript module, you previously had to
go through hoops like embedding JSON in JavaScript just so you can use a regular
import statement, or downloading a file with fetch() and then calling
Response.json(). This is a problem that is now solved in all modern browsers
thanks to JSON module scripts
and import attributes.

The following sample shows how a JSON module script can be imported from inside
a JavaScript module script:

import astronomyPictureOfTheDay from "./apod.json" with { type: "json" };

const {explanation, title, url} = astronomyPictureOfTheDay;

document.querySelector('h2').textContent = title;
document.querySelector('figcaption').textContent = explanation;
Object.assign(document.querySelector('img'), { src: url, alt: title });

There’s no JSON.parse() needed, the JSON is parsed and ready to go right after
the import. This works because the browser knows beforehand that it’s dealing
with JSON, which you declare with the import attribute with { type: "json"
}
.

Check out this
live demo of JSON module imports that
uses the code from the previous listing.

MIME type checking for module scripts is strict. In order for the fetch of the
JSON module script to succeed, the HTTP response must have a JSON MIME type, for
example Content-Type: text/json.

If the with { type: "json" } part of the statement is omitted, the browser
assumes that the intent is to import a JavaScript module script, and the fetch
will fail if the HTTP response has a MIME type that is not a JavaScript MIME
type.

You can
read more about JSON module script processing
in the HTML spec.


Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-06-18 UTC.




Source link