Home  >  Article  >  Web Front-end  >  JSON.parse but without errors

JSON.parse but without errors

Susan Sarandon
Susan SarandonOriginal
2024-10-13 06:17:30686browse

JSON.parse but without errors

Introduction

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.

JSON.tryParse to the rescue

What we can do to fix it is simply introduce the method JSON.tryParse instead.

Implementation

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;
  }
};

Usage

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

Conclusion

This tutorial has helped us work with parsing JSON objects without having to worry about catchig errors every single time.

Happy developing!

The above is the detailed content of JSON.parse but without errors. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn