JSON Parsing in JavaScript
JSON.parse() is a built-in JavaScript function that parses JSON strings into usable JavaScript objects or values. It enables structured data exchange between APIs, services, and front-end applications. To effectively work with JSON in JavaScript, every developer must know how to parse strings into usable objects.
In this tutorial, you will learn how to use JavaScript’s JSON.parse() method to safely convert JSON strings into usable JavaScript objects. We will also explore common parsing issues, API use cases, and best practices for handling JSON.parse() errors in secure applications.
What is JSON Parsing?
- Read and interpret a string written in JSON format
- Convert the string into native JavaScript types like objects and arrays
- Enables structured data access using properties and indexes
How JSON.parse()
Works
- Accepts a valid JSON string and returns the corresponding JavaScript value
- Raises a SyntaxError If the input is not a valid JSON string
- Optional reviver lets you transform values during parsing
- Works in both browsers and Node.js for parsing JSON data
Parsing a JSON String into a JavaScript Object?
Suppose we received a response from a server as a JSON string like below:
JSON.parse() Example
{"user":"Bob","age":25,"admin":false}
The JSON.parse() function parses or converts the JSON string above into the equivalent JavaScript object:
JavaScript Object Equivalent
const obj = { user: "Bob", age: 25, admin: false };
Using JSON.parse()
in JavaScript
Syntax
JSON.parse() Syntax
const obj = JSON.parse(text, reviver);
Parameters
The JSON.parse() method accepts only two parameters:
Parameter | Description |
text | A valid JSON string to be parsed |
reviver | (Optional) A function with (key, value) parameters used to transform each property before returning the final object |
How to Parse JSON String to JavaScript Object
Use JSON.parse() in JavaScript to convert a valid JSON string into a JavaScript object as described in the below example:
Example
const userData = '{"user":"Bob","age":25,"admin":false}'; const obj = JSON.parse(userData); document.getElementById('name').textContent = obj.user; document.getElementById('age').textContent = obj.age; document.getElementById('admin').textContent = obj.admin ? "Yes" : "No";
- userData holds a JSON string representing user information.
- JSON.parse(userData) converts the string into a JavaScript object.
- Access the parsed object using dot notation like obj.user.
Did you know?
JSON.parse()
with a Reviver Function
Example
const employeeData = '{"firstName":"Emma","lastName":"Davis","age":28,"joined":"2020-06-01"}'; const employee = JSON.parse(employeeData, function(key, value) { if (key === "joined") { // Format the joined date into a readable format const date = new Date(value); return date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }); } return value; });
- JSON.parse() is used in combination with a reviver function to process each key–value or name-value pair during parsing.
- Inside the reviver, when the key equals "joined", the date string is converted into a readable format using toLocaleDateString().
- The result is an object where the joined property holds a nicely formatted date instead of the original ISO string.
JSON.parse()
vs JSON.stringify()
- JSON.parse() decodes a JSON string → JavaScript value
- JSON.stringify() encodes a JavaScript value → JSON string
JSON.stringify() Example
const jsObject = { user: "Bob", active: true }; const jsonText = JSON.stringify(jsObject); console.log(jsonText); // '{"user":"Bob","active":true}'
Handling JSON.parse()
Exceptions
What are Exceptions in JavaScript?
Exceptions are unexpected runtime errors that occur during code execution, causing the program to stop or jump to error-handling logic. For instance, JSON.parse() throws a SyntaxError when it encounters invalid JSON syntax, allowing developers to catch and manage the issue without crashing the program.
How to Handle Exceptions While Parsing JSON?
Since JSON.parse() throws a SyntaxError when given invalid or malformed JSON string, it is important to handle such errors to prevent crashes or unexpected behavior.
- Always use a try…catch block around JSON.parse() to catch parsing failures
- Use basic validation or an online JSON linter to check the format before parsing
- Create a reusable safeParse() function that returns fallback data on error
- Log error message and the offending JSON string for easier diagnosis
- Validate input length and basic structure with regex or simple checks before parsing
JSON.parse() Error Handling
// malformed JSON string (missing quotes around age) const badJson = '{"name": "Alice", age:30}'; function safeParse(jsonString) { try { return JSON.parse(jsonString); } catch (err) { console.error('JSON.parse error:', err.message); return null; } }
Parsing Large Integers Safely
JSON numbers larger than JavaScript’s safe integer limit can lose precision. To preserve them, parse them as strings and convert to BigInt in a reviver.
Large Integer Parsing
// JSON with a very large integer const text = '{"id":"9007199254740993","name":"Widget"}'; // Convert the "id" field back into a BigInt const obj = JSON.parse(text, (key, value) => { return key === "id" ? BigInt(value) : value; });
Reviving Custom Class Instances
Class instances are not directly supported in JSON. You can embed a type marker and restore objects using a reviver function.
Custom Type Revival
// Define a class class Point { constructor(x, y) { this.x = x; this.y = y; } } // JSON with a type marker const text = '{"__type":"Point","x":10,"y":20}'; const obj = JSON.parse(text, (key, value) => { if (value && value.__type === "Point") { return new Point(value.x, value.y); } return value; });
Parsing Dates from JSON
JSON has no native date type, so dates are serialized as strings. Use a reviver to convert date strings back into Date objects during parsing.
Date Reviver Example
// JSON with date as ISO string const jsonText = '{"event":"Conference","date":"2025-08-15T09:30:00Z"}'; // Detect ISO date strings (YYYY-MM-DDThh:mm:ssZ) const obj = JSON.parse(jsonText, (key, value) => { if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(value)) { return new Date(value); } return value; });
Parsing and Restoring Functions from JSON
Functions are not part of JSON. Store function bodies as strings, then reconstruct them with Function or eval—with caution for security risks.
Function Revival Example
// JSON containing a function as a string const jsonWithFunc = '{"name":"Calculator","compute":"(x, y) => x * y"}'; const parsed = JSON.parse(jsonWithFunc); parsed.compute = eval(parsed.compute); // or new Function(...)
Caution:
Other Useful Error Handling Techniques
- Use finally for cleanup after try…catch
- Throw custom Error types for clarity
- Propagate errors with throw for centralized handling
- Retry on failure with simple backoff logic
- Catch async errors using .catch() or async/await
- Log issues to tools like Sentry or the console
- Validate inputs before parsing to avoid known errors
Best Practices in Parsing JSON
Following best practices while using JSON.parse() ensures reliable, secure, and high-performance JavaScript applications, especially when working with dynamic or external data sources.
Performance Considerations for JSON Parsing
- Avoid repeatedly calling JSON.parse() on the same string, instead cache parsed results
- For large payloads, use streaming parsers (JSONStream, Jackson StreamingAPI)
- Minimize data size by removing unused fields before parsing
- Benchmark json.parse() in target environment if high throughput is needed
Security Implications of JSON.parse()
- Never parse untrusted JSON without verifying its source as malformed data can crash your app
- Avoid using eval() or third-party JSON parsers that execute code
- Apply strict Content Security Policy (CSP) headers when parsing JSON in the browser
- Sanitize string values if they will be injected into HTML to prevent XSS