JSON IO

JSON.parse typed

Parse is typed `any`, so assert the expected shape right away. The assertion documents intent and unlocks typed access below.

const raw: string = "{\"port\":3000}"; const config = JSON.parse(raw) as { port: number }; console.log(config.port);

3000

The cast does not check the data, it only labels it. The next section adds a light check before trusting the label.

Pretty print

Two extra arguments turn dense JSON into readable text. Human-friendly output matters for files that users may open and edit.

const config = { port: 3000, mode: "dev" }; const text: string = JSON.stringify(config, null, 2); console.log(text);

{
"port": 3000,
"mode": "dev"
}

Config file pattern

Config flow has three steps: read text, parse it, and label the shape. One helper keeps that flow in a single reviewed place.

import { readFileSync, writeFileSync } from "node:fs"; function loadPort(path: string): number { const text: string = readFileSync(path, "utf8"); const data = JSON.parse(text) as { port: number }; return data.port; } writeFileSync("config.json", "{\"port\":3000}", "utf8"); console.log(loadPort("config.json"));

3000

Validate shape simply

Disks hold surprises, from hand edits to half-written saves. Check the one field the program needs before using it.

function isPortConfig(value: unknown): boolean { if (typeof value !== "object" || value === null) { return false; } const port = (value as { port: unknown }).port; return typeof port === "number"; } console.log(isPortConfig({ port: 3000 })); console.log(isPortConfig({ port: "3000" })); console.log(isPortConfig(null));

true
false
false

Return false for null, for non-objects, and for wrong field types. Callers then fall back to defaults instead of crashing later.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What type does TypeScript give to the result of JSON.parse?

    Answer

    any

    The library types the result as any, which is why the page asserts the expected shape at once.

  2. What do the two extra arguments of JSON.stringify control?

    Answer

    A replacer for the values and the indentation of the text

    The replacer can filter or transform values, and the number sets the indent.

  3. What does a simple shape check of parsed JSON test first?

    Answer

    That the value is an object, not null, and the needed field has the right type

    Those three checks cover null, non-objects, and wrong field types before use.

  4. Why validate JSON read from disk?

    Answer

    Files can be hand-edited or half-written

    A config on disk is outside the program, so its shape is not guaranteed by the compiler.

  5. What does this program print? const raw: string = "{\"port\":3000}"; const config = JSON.parse(raw) as { port: number }; console.log(config.port);

    Answer

    3000

    The parsed object has the port field with the number 3000.

  6. What does this program print? console.log(JSON.stringify([1, 2]));

    Answer

    [1,2]

    Without indentation the array is written on one line with no spaces.

  7. What does this program print? console.log(JSON.stringify({ a: 1 }, null, 2).includes("\n"));

    Answer

    true

    The indent argument puts each key on its own line, so the text holds a newline.

  8. What does this program print? console.log(JSON.parse("{\"a\":1}").a);

    Answer

    1

    The parsed object has the key a with the value 1.

  9. What does the compiler say about this program? const config = JSON.parse("{}") as { port: number }; const port: string = config.port; console.log(port);

    Answer

    error TS2322: Type 'number' is not assignable to type 'string'.

    The assertion labels port as a number, so a string variable cannot hold it.

  10. What does the compiler say about this program? const value: unknown = {}; console.log(value.port);

    Answer

    error TS18046: 'value' is of type 'unknown'.

    An unknown value allows no property access until it is checked or asserted.

Article author: Arthur Isaev