How can I safely parse a JSON string and handle errors if the format is incorrect?
Asked on Oct 09, 2025
Answer
To safely parse a JSON string in JavaScript and handle potential errors, you can use a try-catch block around the JSON.parse method. This ensures that if the JSON string is incorrectly formatted, the error is caught and handled gracefully.
<!-- BEGIN COPY / PASTE -->
const jsonString = '{"name": "John", "age": 30}'; // Example JSON string
try {
const data = JSON.parse(jsonString);
console.log("Parsed data:", data);
} catch (error) {
console.error("Error parsing JSON:", error.message);
}
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- The "try" block attempts to parse the JSON string using "JSON.parse".
- If the JSON string is valid, the parsed object is logged to the console.
- If the JSON string is invalid, the "catch" block catches the error and logs an error message.
- This approach prevents your application from crashing due to unhandled exceptions.
Recommended Links:
← Back to All Questions