Avatar ·

How to properly parse JSON in JavaScript? Understanding JSON.parse and error handling

Hello everyone! I'm a beginner in JavaScript and I'm writing a small application that receives data from the server in JSON format. The server returns a string, for example: `'{"name": "John", "age": 30}'`. I'm trying to convert it into an object to work with the fields. The problem is that sometimes everything works, and sometimes the code crashes with an error. I'm using `JSON.parse()`, but when the server returns something unexpected (for example, an empty string or invalid JSON), the application just breaks. Here's my current code: ```javascript const response = '{"name": "John", "age": 30}'; const data = JSON.parse(response); console.log(data.name); // Outputs "John" ``` But if the response is something like: `"not valid json"`, then I get `Uncaught SyntaxError: Unexpected token`. How should I properly handle such situations? Is it necessary to pr