JSON Parse
JSON.parse turns a JSON text into a JavaScript value. Wrap it in try/catch at every untrusted boundary.
Basics
JS
const text = '{"name":"Ada","age":36}';
const user = JSON.parse(text);
user.name; // "Ada"
// Bad input throws SyntaxError
try {
JSON.parse("not json");
} catch (e) {
console.error(e.message);
}
The reviver function — transform values during parsing
JS
// Convert ISO date strings back to Date objects
const reviver = (key, value) => {
if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T/.test(value)) {
return new Date(value);
}
return value;
};
JSON.parse('{"createdAt":"2026-06-06T12:00:00Z"}', reviver);
// { createdAt: Date }
Safe-parse helper
JS
function safeParse(text, fallback = null) {
try { return JSON.parse(text); }
catch { return fallback; }
}
const saved = safeParse(localStorage.getItem("user"), {});
| When parsing fails | Typical fix |
|---|---|
| Truncated response | Check the network — server may have dropped the connection. |
| Trailing comma | Validate against JSON Lint, fix the producer. |
| Wrapped in HTML | Caller sent the wrong URL / hit an error page. |
| BOM at start | JSON.parse(text.replace(/^/, "")) |
Security: Never use
eval() to parse JSON. JSON.parse only ever returns data — eval would execute any code in the string.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JSON Parse!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Safely parse user input that may be malformed.
try { return JSON.
(input); } catch { return null; }
Five letters.
Discussion
Loading…