Safe conversion of JSON string to object in JavaScript
Hello everyone! I'm new to JavaScript and I've run into a problem. I receive data from the server in JSON format, but when I try to convert the string to an object using JSON.parse(), sometimes it works and sometimes it crashes with an error. Here's an example of my code:\n\n```javascript\nconst data = '{"name": "John", "age": 30}';\nconst obj = JSON.parse(data);\nconsole.log(obj.name); // John — works\n```\n\nBut if the string comes from the server in this form:\n\n```javascript\nconst badData = '{name: "John", age: 30}'; // no quotes around keys\nconst obj = JSON.parse(badData); // Throws SyntaxError\n```\n\nOr if the server returned an error as plain text:\n\n```javascript\nconst errorResponse = 'Internal Server Error';\nconst obj = JSON.parse(errorResponse); // Also throws an error\n```\n\nMy program just crashes
No answers yet.
Log in to leave an answer