← All tips

TypeScript: stable JSON parsing helper

typescriptpatterns

Wrap JSON.parse in a try/catch to avoid crashes.

export function safeJson<T>(s: string): T | null {
  try { return JSON.parse(s) as T; } catch { return null; }
}