What is JSON.parse()?
JSON.parse() is a built-in JavaScript method that parses a JSON string and constructs the JavaScript value or object described by the string. It's the opposite of JSON.stringify(), which converts JavaScript objects to JSON strings.
Return Values
JSON.parse() can return any valid JavaScript value: an object, an array, a string, a number, a boolean, or null. The return type depends on the JSON structure. Objects are returned as Object instances, arrays as Array instances.
Error Handling
If the input string is not valid JSON, JSON.parse() throws a SyntaxError. Always wrap JSON.parse() in a try-catch block when parsing untrusted input to handle potential errors gracefully and prevent your application from crashing.
Reviver Function
JSON.parse() accepts an optional second parameter called a "reviver" function. This function is called for each key-value pair and allows you to transform values during parsing. It's useful for converting date strings to Date objects or performing custom transformations.
Security Considerations
JSON.parse() is safe to use with untrusted data because it only parses JSON. Unlike eval(), it won't execute arbitrary JavaScript code. Always use JSON.parse() instead of eval() when parsing JSON data from external sources.
Browser Support
JSON.parse() is supported in all modern browsers and has been available since IE8, Firefox 3.5, Chrome 3, and Safari 4. In Node.js, it's been available since the very first version. No polyfill is needed for modern development.