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 aparse
method to convert a string into an object. -
Enclose
parse
method intry 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
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
Summary
To Sump up, Learned variable type is JSON object or not using
- JSOn parse method
- npm libraries kindOf