Sub topic 17
Importing JSON with Import Attributes
This chapter assumes you already know static import syntax, default exports, and how modules load in browsers and Node.js. You should also know that modules are evaluated once and cached, as earlier chapters described. Here you will learn how to import a JSON file as a module, why the language makes you declare the file's type, and when reading the file yourself is the better choice.
The Basic Form
A JSON module is a JSON file loaded through the module system. To import one, you add an import attribute. An import attribute is a key-value pair written after the specifier with the with keyword. It tells the host (the browser or Node.js) what kind of module you expect.
Start with a data file:
{
"name": "geometry",
"version": "1.0.0",
"features": ["area", "perimeter"]
}Save it as config.json. Then import it from a module next to it:
// main.js
import config from './config.json' with { type: 'json' };
console.log(config.name); // geometry
console.log(config.features.length); // 2The type: 'json' attribute is required. If you leave it out, the import fails. The parsed JSON value becomes the module's default export. That value can be an object, an array, a string, a number, a boolean, or null.
Why the Type Must Be Declared
Browsers decide how to treat a fetched module from the server's Content-Type header, not from the file extension. Suppose you import https://cdn.example.com/data.json and expect inert data. If the server, or an attacker who controls it, responds with text/javascript, a loader that trusted the server would run that response as code. A file you expected to be data would then be executing with your page's privileges.
The attribute closes that gap. You state the type you expect, and the host checks it:
- With
type: 'json', the response must be JSON. The browser requires a JSON MIME type such asapplication/json. The content is parsed and never executed. - Without an attribute, the host expects JavaScript. A browser rejects a response served as
application/json. Node.js throwsERR_IMPORT_ATTRIBUTE_MISSING.
Only a Default Export
A JSON module has exactly one export, default. Top-level keys do not turn into named exports:
// SyntaxError: The requested module './config.json'
// does not provide an export named 'name'
import { name } from './config.json' with { type: 'json' };Destructure after a default import instead:
import config from './config.json' with { type: 'json' };
const { name, version } = config;
console.log(`${name}@${version}`);Other Import Forms
Attributes work with the other static forms too. A namespace import gives you an object with a single default property:
import * as configModule from './config.json' with { type: 'json' };
console.log(configModule.default.name); // geometryRe-exports take the same clause. Use this when you want a barrel module to expose your data:
// settings/index.js
export { default as config } from '../config.json' with { type: 'json' };Dynamic import() takes the attributes as a second argument, inside an options object with a with key:
// load-locale.js
export async function loadLocale(lang) {
const module = await import(`./locales/${lang}.json`, {
with: { type: 'json' },
});
return module.default;
}The promise resolves to the namespace object, so you read .default. The dynamic form is useful when the file name depends on runtime input, such as a language code, or when the data is large and needed only sometimes.
JSON Modules Are Shared Singletons
A JSON module is cached like any other module. Every importer gets the same object. That object is not frozen, so a mutation made by one importer is visible to all the others:
// a.js
import config from './config.json' with { type: 'json' };
config.features.push('volume');
// b.js
import config from './config.json' with { type: 'json' };
export function featureCount() {
return config.features.length;
}
// main.js
import './a.js';
import { featureCount } from './b.js';
console.log(featureCount()); // 3, not 2Here main.js imports a.js first, so the push runs before featureCount is called. If you need a private copy, clone the data with structuredClone(config). If no code should ever change it, call Object.freeze on it once, in the module that owns the data.
The cache also means that editing config.json while the program runs has no effect. The file is read once. A query string such as ./config.json?v=2 makes a new specifier and therefore a new module instance. That is a workaround and does not reload the module. Each variant stays in memory.
The Older assert Syntax
Earlier drafts of this feature used the keyword assert:
// Obsolete: do not use in new code
import config from './config.json' assert { type: 'json' };The proposal was renamed import attributes and switched to with. Part of the reason was that hosts needed the attribute to affect how a module loads, and not only check it after loading. V8 has removed assert, so current Chrome and Node.js 22 and later reject it. Node.js 18.20 and later accept with. If you maintain old code, replacing assert with with is a mechanical change.
Choosing Between Import and Reading the File
Importing JSON is not always the right tool. Compare it with the alternatives:
| Approach | Loads when | Failure behavior | Re-reads changes | Works in |
|---|---|---|---|---|
| `import ... with { type: 'json' }` | Before the module body runs | Whole module graph fails to load | No, cached | Browsers, Node.js, Deno |
| `await import(..., { with })` | When called | Rejected promise you can catch | No, cached per URL | Browsers, Node.js, Deno |
| `readFile` + `JSON.parse` | When called | Exception you can catch | Yes | Node.js |
| `fetch(url).then(r => r.json())` | When called | Rejected promise you can catch | Yes, subject to HTTP caching | Browsers, Node.js 18+ |
| `createRequire(...)('./x.json')` | When called | Exception you can catch | No, cached | Node.js |
A static JSON import fits configuration and fixed data that ship with your code: lookup tables, translations bundled at build time, package metadata. Read the file yourself when the data might be missing, when you want to recover from malformed content, when you need fresh data on each read, or when the path comes from user input. A previous chapter showed the Node.js pattern of new URL('./settings.json', import.meta.url) passed to readFile, which resolves the path relative to the module just as an import would.
Common Errors
ERR_IMPORT_ATTRIBUTE_MISSING(Node.js): you imported a.jsonfile withoutwith { type: 'json' }.Unexpected identifier 'assert'or a similar SyntaxError: the runtime has droppedassert. Switch towith.- "does not provide an export named": you used a named import. Import the default and destructure it.
- Failed module script, MIME type error (browser): the server sends
.jsonfiles with the wrongContent-Type, or you left out the attribute. Check both. SyntaxErrorpointing into the JSON: the file is not valid JSON. Comments and trailing commas are not allowed. Because a static import fails at link time, one bad file stops the whole application from starting.
Exercise
A Node.js module contains import { port } from './server.json' with { type: 'json' }; and fails at startup. server.json is valid and contains {"port": 8080}. What is wrong, and what is the fix?
Show answer
A JSON module exposes only a default export, so the named import port does not exist and linking throws a SyntaxError. Import the default and destructure it: import server from './server.json' with { type: 'json' }; const { port } = server;
Exercise
Two modules import the same flags.json with the type attribute. Module A sets flags.beta = true. Module B logs flags.beta after A has run. What does B log, and how would you stop A's change from leaking into B?
Show answer
B logs true, because both imports share one cached module instance and the parsed object is not frozen. To prevent this, have A work on a copy (const local = structuredClone(flags)), or freeze the object in one owning module and have the others import it from there.
Exercise
You need to load locales/${lang}.json where lang comes from the user's browser settings, and you want to fall back to English if the file does not exist. Write the loading code.
Show answer
Use dynamic import with attributes inside try/catch: async function load(lang) { try { return (await import(./locales/${lang}.json, { with: { type: 'json' } })).default; } catch { return (await import('./locales/en.json', { with: { type: 'json' } })).default; } }. A static import cannot do this, because its specifier must be a fixed string and a failure would stop the whole module graph.