How to check if the object type is JSON in javascript

It is a short tutorial about how to check if an object is JSON in JavaScript and typescript.

JSON is simple data with keys and values enclosed in parentheses.

JSON objects don’t have type representation in javascript, They are treated as normal strings.

Sometimes, We might think and need to answer the below questions for

  • Check whether a string is a valid json object or not
  • Find an Object in json format
  • String variable is json parsable or not

How to check object variable is JSON in javascript

Multiple ways to check whether an object is json or not

Use JSON parse method

  • Javascript has a JSON class that has a parse method to convert a string into an object.
  • Enclose the parse method in the try and catch block
  • It throws an error if JSON is not parsable

Here is a function to check string is valid JSON or not. Returns true for valid JSON object, false for invalid JSON data

function isJsonObject(strData) {
  try {
    JSON.parse(strData);
  } catch (e) {
    return false;
  }
  return true;
}
let jsondata = '{"username": "admin"}';
let notjsondata = "username-admin";
console.log(isJsonObject(jsondata)); // returns true
console.log(isJsonObject(notjsondata)); // returns false

Use object constructor

In javascript, JSON is an instance of an Object,

To check if an object is JSON, check first, it is an instanceOf an Object and its constructor is an Object.

Here is an example

function isJsonObject(strData) {
 return strData instanceof Object && strData.constructor === Object
}
let jsondata = '{"username": "admin"}';
let notjsondata = "username-admin";
console.log(isJsonObject(jsondata)); // returns true
console.log(isJsonObject(notjsondata)); // returns false

Check object type using the npm library

There are many npm libraries to check native object types.

Following are two node libraries

  • @sindresorhus/is
  • kind-of

We are going to write an example for the kindOf npm library.

First, install using the npm command.

npm install  kind-of --save-dev

Here is a simple program to check types of data

var kindOf = require("kind-of");

console.log(kindOf(12312)); // returns number
console.log(kindOf("test")); // returns string
console.log(kindOf(false)); // returns boolean

kindOf({ username: "admin" }); // object

Summary

To Sump up, Learned variable type is JSON object or not using

  • JSOn parse method
  • npm libraries kindOf