How can I parse a JSON string in JavaScript and handle potential errors?
Asked on Oct 08, 2025
Answer
To parse a JSON string in JavaScript and handle potential errors, you can use the "JSON.parse" method within a "try...catch" block. This allows you to catch any errors that occur during parsing.
<!-- BEGIN COPY / PASTE -->
const jsonString = '{"name": "John", "age": 30}';
try {
const parsedData = JSON.parse(jsonString);
console.log(parsedData.name); // Output: John
} catch (error) {
console.error("Invalid JSON string:", error.message);
}
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- Use "JSON.parse" to convert a JSON string into a JavaScript object.
- Wrap the "JSON.parse" call in a "try...catch" block to handle any syntax errors in the JSON string.
- In the "catch" block, you can log or handle the error as needed.
Recommended Links:
← Back to All Questions