How to generate zod schemas for safe runtime json parsing
- Step 1Identify unsafe JSON.parse() calls — Search the codebase for JSON.parse calls: grep -r 'JSON.parse' src/. Each call that parses external data (localStorage, API, WebSocket, postMessage) is a candidate for Zod validation.
- Step 2Generate the Zod schema for the parsed shape — Log an example of the parsed value: console.log(JSON.stringify(JSON.parse(rawData), null, 2)). Paste the result here and generate the Zod schema.
- Step 3Replace the unsafe parse call — Before: const data = JSON.parse(stored) as UserPreferences. After: const parsed = UserPreferencesSchema.safeParse(JSON.parse(stored)); if (!parsed.success) { /* handle corrupt data */ return defaults; } const data = parsed.data.
- Step 4Handle schema version migrations — When stored JSON data may be from an older schema version, use .catch() to provide defaults: const schema = z.object({ theme: z.string().catch('light'), fontSize: z.number().catch(14) }). Old data that is missing new fields gets the default value instead of failing validation.
Frequently asked questions
How do I handle localStorage data that may have been written by an older version of the app?+
Use z.object().partial() to make all fields optional for backward compatibility with old data formats, then fill missing fields with defaults after parsing. Alternatively, use .catch(defaultValue) on individual fields to provide defaults for missing or malformed values.
What happens when JSON.parse() itself throws — for example on malformed JSON?+
Zod's .parse() and .safeParse() methods parse a JavaScript value, not a JSON string — they receive the result of JSON.parse(). Wrap JSON.parse() in a try/catch first: try { const raw = JSON.parse(str); const result = schema.safeParse(raw); } catch { /* handle malformed JSON */ }. Or use the zod-json package which combines JSON.parse and Zod parsing.
Is the external data transmitted to JAD Apps?+
No. Schema generation runs entirely in your browser. Data from localStorage, WebSockets, and external APIs is never transmitted to JAD Apps servers.
Privacy first
Conversion runs locally in your browser. No file is uploaded — only metadata counters are saved for signed-in dashboard stats.