JSON.parse() in JavaScript
Learn JSON.parse() in JavaScript: parsing strings to objects, the reviver function, error handling, and security considerations for parsing untrusted JSON input.
Detailed Explanation
JSON.parse() is the built-in JavaScript method for converting a JSON-formatted string into a native JavaScript value. It is the counterpart to JSON.stringify() and is used whenever you receive JSON data from an API, read from localStorage, or process JSON files.
Method signature:
JSON.parse(text, reviver?)
- text: The JSON string to parse (must be valid JSON)
- reviver: Optional function that transforms parsed values
Basic usage:
const data = JSON.parse('{"name":"Alice","age":30}');
console.log(data.name); // "Alice"
console.log(data.age); // 30
The reviver parameter:
A reviver function is called for every key-value pair during parsing, allowing you to transform values. A common use case is converting date strings back into Date objects:
const data = JSON.parse(jsonString, (key, value) => {
if (key === 'createdAt' || key === 'updatedAt') {
return new Date(value);
}
return value;
});
The reviver walks the parsed tree from the leaves to the root, so nested values are transformed before their parents.
Error handling:
JSON.parse() throws a SyntaxError when the input is not valid JSON. You should always wrap it in a try/catch block:
try {
const data = JSON.parse(userInput);
} catch (error) {
console.error('Invalid JSON:', error.message);
}
The error message varies by JavaScript engine but typically includes the position where parsing failed.
Security considerations:
In older JavaScript environments, developers sometimes used eval() to parse JSON, which is extremely dangerous because eval() executes arbitrary code. JSON.parse() is safe in this regard — it only parses data and cannot execute functions or access variables. However, parsing untrusted JSON can still be a vector for prototype pollution attacks if the parsed object is naively merged with other objects. Libraries like lodash.merge have had vulnerabilities where keys like __proto__ or constructor in parsed JSON could modify object prototypes.
Common mistakes developers make:
A frequent error is calling JSON.parse() on a value that is already a JavaScript object, which fails because JSON.parse() expects a string. Check typeof value === 'string' before parsing. Another mistake is not handling the error case, allowing a malformed response from an API to crash the entire application. Developers also sometimes parse JSON inside a loop without realizing the performance cost — parse once and cache the result. Additionally, calling JSON.parse("undefined") or JSON.parse("") throws an error because neither is valid JSON.
Best practices:
Always use try/catch around JSON.parse(). Validate the parsed data against your expected schema rather than trusting the structure blindly. Use the reviver function to transform dates, BigInt values, or other types that JSON does not natively support. When parsing large JSON strings, consider streaming parsers for better memory efficiency.
Use Case
Parsing a JSON response from a REST API fetch() call and using a reviver function to automatically convert ISO 8601 date strings into JavaScript Date objects.