JSON Parse
JSON.parse() converts a JSON-formatted string into a live JavaScript value, and its optional reviver function lets you transform data as it's built.
What JSON.parse() Does
JSON.parse() takes a string containing valid JSON text and returns the corresponding JavaScript value — typically an object or array, but it can also return a bare string, number, boolean, or null if that's all the input contains. If the string is not valid JSON, it throws a SyntaxError.
Basic Parsing
<!DOCTYPE html>
<html>
<body>
<h2>Result</h2>
<p id="demo"></p>
<script>
const jsonText = '{"name": "Kenji", "age": 34, "active": true}';
const user = JSON.parse(jsonText);
console.log(user.name); // "Kenji"
console.log(user.age); // 34
console.log(typeof user); // "object"
</script>
</body>
</html>Handling Parse Errors
Because JSON.parse() throws on malformed input, it should almost always be wrapped in a try/catch block when the source of the string isn't fully trusted — such as data from a network request, a file, or user input.
Safe Parsing With try/catch
<!DOCTYPE html>
<html>
<body>
<h2>Result</h2>
<p id="demo"></p>
<script>
function safeParse(text) {
try {
return JSON.parse(text);
} catch (err) {
console.error("Invalid JSON:", err.message);
return null;
}
}
safeParse('{"valid": true}'); // { valid: true }
safeParse("{invalid}"); // logs error, returns null
</script>
</body>
</html>The Reviver Function
JSON.parse() accepts an optional second argument called a reviver: a function called for every key/value pair in the resulting structure, from the innermost values outward. The reviver receives (key, value) and returns the value to use in the final result — return undefined to delete that key entirely.
Reviving Date Strings Into Date Objects
<!DOCTYPE html>
<html>
<body>
<h2>Result</h2>
<p id="demo"></p>
<script>
const raw = '{"event": "Launch", "date": "2024-05-01T09:00:00Z"}';
const parsed = JSON.parse(raw, (key, value) => {
if (key === "date") {
return new Date(value);
}
return value;
});
console.log(parsed.date instanceof Date); // true
console.log(parsed.date.getFullYear()); // 2024
</script>
</body>
</html>Using the Reviver to Filter Data
Because returning undefined from the reviver removes a key, it's also useful for stripping out fields you don't want to keep, such as internal or sensitive properties returned by an API.
Dropping a Key During Parse
<!DOCTYPE html>
<html>
<body>
<h2>Result</h2>
<p id="demo"></p>
<script>
const raw = '{"id": 1, "name": "Item A", "internalCode": "X99-SECRET"}';
const cleaned = JSON.parse(raw, (key, value) =>
key === "internalCode" ? undefined : value
);
console.log(cleaned); // { id: 1, name: "Item A" }
</script>
</body>
</html>Reviver Call Order
The reviver runs bottom-up: nested values are processed before their parent object or array, and finally an empty-string key call happens on the whole result, letting you transform the root value itself.
Exercise: JSON Parse
What does JSON.parse() do?