How to check if the object type is JSON in javascript
- Admin
- Sep 20, 2023
- Javascript
It is a short tutorial about how to check an object in 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 treat 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
- Javascript has a
JSON
class that has aparse
method to convert a string into an object. - Enclose the
parse
method in thetry 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 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