Basic Parsing and Stringify

JSON.parse(string) converts a valid JSON string to a JavaScript value. JSON.stringify(value) converts a JavaScript value to a JSON string. These two functions are the foundation of all JSON handling in JavaScript. JSON.stringify accepts optional replacer and space arguments for transformation and formatting.

Handling Parse Errors

JSON.parse throws a SyntaxError if the input is not valid JSON. Always wrap parse calls in try-catch when the input source is untrusted or potentially malformed. The error message includes the position of the syntax problem, useful for debugging.

The JSON BigInt Problem

JavaScript uses 64-bit floating-point for all numbers. Integers larger than 2^53-1 cannot be represented exactly. JSON from APIs that use large integer IDs may silently lose precision when parsed. The solution is receiving large integers as strings or using a JSON parser that supports BigInt.

Type Safety After Parsing

JSON.parse returns 'any' in TypeScript. Always validate the structure of parsed external data before trusting it. Runtime validation libraries like Zod, Yup, or io-ts can parse and type-check JSON simultaneously, throwing descriptive errors when structure doesn't match expectations.

Key Takeaway

JSON.parse is simple but has important edge cases around error handling and number precision. Always handle SyntaxError, validate structure before use, and be aware of BigInt limitations when parsing ID fields.