Sub topic 17
Importing JSON with Import Attributes
This chapter assumes you already know the import forms covered earlier: default, named, and namespace imports. It also assumes you can run a module in either a browser or Node.js.
Why JSON Needs an Attribute
A module specifier only says where a file is. It says nothing about what kind of file it is. Browsers judge a response by its MIME type, so a compromised or misconfigured server could send back JavaScript where you expected data, and that JavaScript would run. An import attribute prevents this. It states the module type you expect, and the host refuses to load the file if what it receives doesn't match.
import config from './config.json' with { type: 'json' };
console.log(config.name);The with { type: 'json' } clause is the attribute. If you leave it out, the import fails. Browsers report a MIME type error, and Node.js throws ERR_IMPORT_ATTRIBUTE_MISSING.
What a JSON Module Exports
A JSON module has exactly one export, the default export, which holds the parsed value. Named imports do not work:
// SyntaxError: config.json does not provide an export named 'name'
import { name } from './config.json' with { type: 'json' };To get at individual fields, import the default export and destructure it in a separate statement:
import config from './config.json' with { type: 'json' };
const { name, version } = config;
console.log(name, version);A JSON module follows the same singleton rule as any other module. Every importer receives the same object. If one module mutates it, all the others see the change. Treat the object as read-only, or copy it with structuredClone(config) before you modify it.
Dynamic Import with Attributes
import() takes the attributes in a second options argument:
const { default: messages } = await import('./messages.en.json', {
with: { type: 'json' }
});
console.log(messages.greeting);This works well for data you only sometimes need, such as locale files.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Missing attribute error | `with { type: 'json' }` omitted | Add the attribute |
| No export named `x` | Named import from JSON | Import the default export, then destructure |
| MIME type error in the browser | Server does not send `application/json` | Fix the server's content type |
| Unexpected token `assert` | Old import assertion syntax | Replace `assert` with `with` |
Exercise
A module contains import { port } from './server.json' with { type: 'json' };. Why does it fail, and how do you fix it?
Show answer
JSON modules expose only a default export, so there is no named export called port. Fix it by writing import server from './server.json' with { type: 'json' }; and then const { port } = server;.
Exercise
Two modules both import settings.json. One of them runs settings.debug = true. What does the other module see, and why?
Show answer
The other module sees debug as true. A JSON module is evaluated once and shared as a singleton, so both importers hold the same object.