We've all been in the situation where we simply want to call JSON.parse and not get an error if the value we're trying to parse is null or undefined.
What we can do to fix it is simply introduce the method JSON.tryParse instead.
Simply define this function in your application at the beginning and make it globally available.
JSON.tryParse = function (value) { try { return JSON.parse(value); } catch (error) { return null; } };
Let's say you want to retreive a cached user without having to try/cacth. This is how:
const user = JSON.tryParse(localStorage.getItem("user")); // returns "null" instead of throwing an error in case there is no entry
This tutorial has helped us work with parsing JSON objects without having to worry about catchig errors every single time.
Happy developing!
위 내용은 JSON.parse이지만 오류는 없습니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!