Sub topic 2
What a JSON Module Is
This chapter assumes you know how ES modules use import and export, how JSON.parse turns text into values, and how to run a module script in a browser or Node.js. The previous chapter covered how the module loader fetches, links, and evaluates a graph of modules. This chapter applies that model to a different kind of module: one whose source is JSON text, not JavaScript.
The core idea
A JSON module is a module created from a JSON file. The loader reads the file, parses it as JSON, and wraps the parsed value in a module whose only export is default. Importing that module gives you the parsed value. The file is never executed as code.
The examples in this chapter use this file:
{
"appName": "Inventory",
"version": 3,
"features": ["search", "export"]
}Save it as config.json. A module next to it can import it like this:
import config from "./config.json" with { type: "json" };
console.log(config.appName); // "Inventory"
console.log(config.features[0]); // "search"The with { type: "json" } part is an import attribute. It tells the host that you expect a JSON module. The next chapter covers the syntax, and the chapter after that explains why the attribute is required. For now, treat it as the fixed phrase that turns JSON loading on.
How a JSON module differs from a JavaScript module
A JavaScript module is source code. The engine parses it, finds its import and export declarations, links it to its dependencies, and runs its top-level code during evaluation. A JSON module has none of those parts. It has no imports, no export declarations, and no code to run.
The ECMAScript specification models it as a Synthetic Module Record. A synthetic module is one the host builds directly. The module's exports are not derived from parsing source code. For JSON, the host builds a record with exactly one export name, default, and sets it to the value JSON.parse would return for the file's text.
| Property | JavaScript module | JSON module |
|---|---|---|
| Source format | JavaScript code | JSON text |
| Can import other modules | Yes | No |
| Export names | Whatever the code declares | Only `default` |
| Top-level code runs | Yes, during evaluation | No code exists |
| Position in the module graph | Anywhere | Always a leaf |
| How the value is produced | Running the module body | Parsing with JSON rules |
The last two rows matter most. A JSON module cannot depend on anything, so it is always a leaf node in the module graph. Its value is fixed by the parse, so evaluating it has no side effects and cannot be affected by evaluation order.
Looking inside the module namespace
Every module has a namespace object that lists its exports. You can inspect a JSON module's namespace with a namespace import:
import * as ns from "./config.json" with { type: "json" };
console.log(Object.keys(ns)); // [ 'default' ]
console.log(ns[Symbol.toStringTag]); // "Module"
console.log(ns.default.appName); // "Inventory"
console.log("appName" in ns); // falseThe namespace has exactly one key, default. The JSON object's own keys such as appName are not exports. They are properties of the object stored in default. A later chapter covers what this means for named imports. The short version is that import { appName } from ... looks for an export called appName, and there isn't one.
JSON rules, not JavaScript rules
The file is parsed with the JSON grammar, the same grammar JSON.parse uses. That grammar is much stricter than a JavaScript object literal, and many load failures come from treating a .json file like JavaScript.
| Content in the file | JavaScript object literal | JSON module |
|---|---|---|
| `// comment` or `/* comment */` | Allowed | SyntaxError |
| Trailing comma `[1, 2,]` | Allowed | SyntaxError |
| Unquoted key `{ name: "x" }` | Allowed | SyntaxError |
| Single-quoted string `'x'` | Allowed | SyntaxError |
| `undefined`, `NaN`, `Infinity` | Allowed | SyntaxError |
| Functions, `Date`, regex literals | Allowed | SyntaxError |
If the text fails to parse, the module fails to load. An error in a static import fails the whole module graph, so none of the modules in that graph run, including the one that imported the JSON. Formats such as JSONC or JSON5, used by some editor and compiler config files, allow comments and trailing commas. Those files are not valid JSON and cannot be loaded as JSON modules.
Any JSON value can be the default export
The top level of a JSON file does not have to be an object. Any JSON value is valid, and it becomes the default export as is.
Save this as colors.json:
["red", "green", "blue"]Then import it:
import colors from "./colors.json" with { type: "json" };
console.log(Array.isArray(colors)); // true
console.log(colors.length); // 3A file containing only 42, "hello", true, or null is also a valid JSON module. Its default export is that number, string, boolean, or null. This is rarely useful, but it shows that the default export is just the parsed value and nothing more.
Edge cases inherited from JSON.parse
Because the value matches what JSON.parse produces, the quirks of JSON.parse carry over.
- Duplicate keys:
{"a": 1, "a": 2}parses without error, and the last value wins, soais2. Nothing warns you. - Large integers: JSON numbers become JavaScript numbers, which are 64-bit floats.
9007199254740993loses precision and becomes9007199254740992. Store IDs that large as strings. - The
__proto__key:JSON.parsecreates an ordinary own property named__proto__. It does not change the object's prototype. This is safer than a JavaScript object literal, where__proto__:does set the prototype. - No reviver:
JSON.parseaccepts a reviver function to transform values during parsing. A JSON module has no way to pass one, so date strings stay strings until you convert them yourself. - Plain data only: you get ordinary objects with
Object.prototypeand ordinary arrays. They are not frozen, and a later chapter explains why that matters when many modules share them.
You can confirm the precision and duplicate-key behavior with a small Node.js script. Save it as quirks.json:
{ "id": 9007199254740993, "mode": "dev", "mode": "prod" }Then run this module:
import quirks from "./quirks.json" with { type: "json" };
console.log(quirks.id); // 9007199254740992
console.log(quirks.mode); // "prod"Where the type information comes from
The engine itself does not open files. The host does: the browser or Node.js. The host decides how to locate and read the file, and it must confirm that the result really is JSON before it builds the module. In a browser, that means checking the response's MIME type, for example application/json. In Node.js, it means the file's extension and the import attribute. Later chapters cover each environment in detail. The point to keep from this chapter is that a JSON module comes from two pieces of information that must agree: your code's declared expectation (type: "json") and the host's evidence about the resource.
Summary of the mental model
- A JSON module is a synthetic module built from parsed JSON text.
- It has exactly one export,
default, holding the parsed value. - It has no dependencies and runs no code, so it is always a leaf in the graph.
- Its contents follow strict JSON grammar and inherit every
JSON.parsequirk. - Invalid JSON in a static import fails the whole module graph.
Exercise
A teammate adds a comment line // default settings to the top of config.json, which main.js imports statically with with { type: "json" }. main.js also logs "starting" on its first line. What happens when main.js runs, and why?
Show answer
Nothing in main.js runs, so "starting" is never logged. The JSON grammar does not allow comments, so parsing config.json throws a SyntaxError while the module graph is loading. A static import failure prevents the entire graph from evaluating, including main.js.
Exercise
Given import * as ns from "./colors.json" with { type: "json" }; where colors.json contains ["red", "green"], what do Object.keys(ns) and ns.default[1] return?
Show answer
Object.keys(ns) returns ["default"], because a JSON module's namespace has only the default export. ns.default[1] returns "green", because the default export is the parsed array.
Exercise
An orders.json file contains {"orderId": 12345678901234567890}. After importing it as a JSON module, the code compares orders.orderId against an ID from the database and the comparison fails. What is the likely cause, and how do you fix it?
Show answer
JSON numbers are parsed into 64-bit floating-point JavaScript numbers, so integers above Number.MAXSAFEINTEGER (9007199254740991) lose precision. Store the ID as a string in the JSON, for example "12345678901234567890", and compare it as a string or convert it with BigInt.