How to check if object type is JSON in javascript

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

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

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

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

  • Check a string is a valid json object or not

  • Find an Object in json format

  • String variable is json parsable or not

  • Javascript has a JSON class that has a parse method to convert a string into an object.

  • Enclose parse method in 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 {
    } 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

Check object type using 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 kindOf npm library.

First, install using 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


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

  • JSOn parse method
  • npm libraries kindOf
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.