How to check if the given Input Is JSON or not?

Introduction

Sometimes we need to perform different operations depending upon the type of the given input value. In this post, we will see how to check if the type of any given input is JSON or not? 
The following method will take the input as an argument and return true if the input is of type JSON or false if it is not JSON. Let us see the below method for the same:

  function isJson(payload: string): boolean {
        if (payload) {
            try {
                payload = JSON.parse(payload);
            } catch (e) {
                return false;
            }
            return (typeof payload === "object" && payload !== null);
        } else {
            return false;
        }
    }
The above method can be used at various places in our application where we need to perform some action if the input is JSON type.

Example: We will check if the given result is JSON then we can parse it using the parse method called JSON.parse(). This additional check using isJson method will avoid errors in our code.

Example: var result = result && isJson(result) ? JSON.stringify(JSON.parse(result), undefined, 3) : result;

Comments