How to use Constructor Type Checking In Javascript
In this approach, we are using Object.prototype.toString.call(obj) to get the constructor type of the object and compare it to [object Object], making sure it’s a plain object. We also verify that the object is not an array using Array.isArray(obj), thus determining if it’s JSON-like.
Syntax:
Object.prototype.toString.call(obj) === '[object Object]' && !Array.isArray(obj);
Example 1: The below example uses Constructor Type Checking to check if the object is JSON in JavaScript.
const obj = {
name: "GFG",
age: 30,
city: "Noida"
};
const obj2 = new Date();
const isJSON = Object
.prototype
.toString
.call(obj) === '[object Object]'
&&
!Array
.isArray(obj);
const isJSON2 = Object
.prototype
.toString
.call(obj2) === '[object Object]'
&&
!Array
.isArray(obj2);
console.log(isJSON);
console.log(isJSON2);
Output
true false
Example 2: Determining if an object matches JSON structure using a function, then checking user and car objects to validate JSON likeness.
function isJSONObject(obj) {
return obj !== null
&&
typeof obj === 'object'
&&
obj.constructor === Object;
}
const user = {
username: "GFG",
email: "gfg@gmail.com",
age: 25
};
const car = {
make: "Toyota",
model: "Camry",
year: 2020
};
const isJSONUser = isJSONObject(user);
const isJSONCar = isJSONObject(car);
console.log(isJSONUser);
console.log(isJSONCar);
Output
true true
How to Check if Object is JSON in JavaScript ?
JSON is used to store and exchange data in a structured format. To check if an object is JSON in JavaScript, you can use various approaches and methods. There are several possible approaches to check if the object is JSON in JavaScript which are as follows:
Table of Content
- Using Constructor Type Checking
- Using instanceof