iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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 failsTypical fix
Truncated responseCheck the network — server may have dropped the connection.
Trailing commaValidate against JSON Lint, fix the producer.
Wrapped in HTMLCaller sent the wrong URL / hit an error page.
BOM at startJSON.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; }

Test yourself

Q1. Invalid JSON passed to JSON.parse causes…
Q2. JSON.parse's second argument is called…
Q3. Never use … instead of JSON.parse…

Discussion

Loading…