DEV Community

Cover image for JSON.parse without errors
Amjad Abujamous
Amjad Abujamous

Posted on

JSON.parse 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;
  }
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Conclusion

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

Happy developing!

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit