1. Parsing JSON Strings (`JSON.parse`)

`JSON.parse()` turns a JSON string into a native JavaScript object, array, or primitive. You can pass an optional `reviver` function to transform values during parsing (e.g. converting ISO date strings into Date objects).

Parsing JSON with a Reviver Function
const jsonString = '{"id": 42, "name": "Sarah", "created": "2026-07-25T12:00:00.000Z"}';

// Parse string and revive date strings into Date instances
const user = JSON.parse(jsonString, (key, value) => {
  if (key === 'created') return new Date(value);
  return value;
});

console.log(user.created instanceof Date); // true
console.log(user.created.getFullYear()); // 2026

Explanation: The reviver function intercepting `JSON.parse` converts date strings into native Date objects.

Pro Tips

  • Always wrap `JSON.parse()` in a `try...catch` block to prevent application crashes on invalid JSON.
  • Never pass untrusted user input directly to `eval()`; always use `JSON.parse()`.

2. Pretty Printing & Minifying (`JSON.stringify`)

`JSON.stringify(value, replacer, space)` accepts a third `space` parameter to format JSON into multi-line indented strings. Passing `2` or `4` creates formatted JSON. Leaving `space` undefined creates minified single-line JSON.

Formatting and Filtering with JSON.stringify
const payload = {
  id: 101,
  title: "API Update",
  secretKey: "super_secret_token",
  tags: ["web", "json"]
};

// 1. Pretty print with 2-space indentation
const formatted = JSON.stringify(payload, null, 2);

// 2. Replacer array: Only stringify specific keys (omit secretKey)
const sanitized = JSON.stringify(payload, ["id", "title", "tags"], 2);

console.log(sanitized);

Explanation: The `replacer` argument allows filtering specific properties during stringification.

3. TypeScript Type Assertions for API Responses

In TypeScript, `JSON.parse()` returns type `any`. For type safety, define a TypeScript `interface` or `type` and assert or validate the parsed object.

Type-Safe JSON Parsing in TypeScript
interface ApiResponse {
  id: number;
  status: 'active' | 'pending';
  payload: Record<string, unknown>;
}

const rawJson = '{"id": 1, "status": "active", "payload": {}}';

// Type assertion for parsed payload
const response = JSON.parse(rawJson) as ApiResponse;

console.log(response.status.toUpperCase()); // ACTIVE

Explanation: Asserting or validating the TypeScript type ensures IDE autocomplete and compile-time type safety.