Categories
JavaScript Answers

How to check if JavaScript object is JSON?

Spread the love

Sometimes, we want to check if JavaScript object is JSON.

In this article, we’ll look at how to check if JavaScript object is JSON.

How to check if JavaScript object is JSON?

To check if JavaScript object is JSON, we can use the JSON.parse method.

For instance, we write

const isJson = (data) => {
  try {
    const testIfJson = JSON.parse(data);
    if (typeof testIfJson === "object") {
      return true;
    } else {
      return false;
    }
  } catch {
    return false;
  }
};

to call JSON.parse with data to parse the data string.

If its type is 'object', then it’s JSON is it’s not null.

Otherwise, it’s not JSON.

If JSON.parse can’t parse data, an error will be thrown and false is returned since it’s not JSON.

Conclusion

To check if JavaScript object is JSON, we can use the JSON.parse method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *