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
Using Constructor Type Checking
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
Using instanceof
In this approach, we are using the instanceof operator to check if the object is an instance of the Object class and not an array, making sure it’s a plain JSON object.
Syntax:
let gfg = objectName instanceof objectType
Example 1: The below example uses instanceof to check if the object is json in JavaScript or not.
const obj = {
name: "GFG",
age: 30,
city: "Noida"
};
const obj2 = ["1", "2", "3"];
const isJSON = obj instanceof Object && !Array
.isArray(obj);
const isJSON2 = obj2 instanceof Object && !Array
.isArray(obj2);
console.log(isJSON);
console.log(isJSON2);
Output
true false
Example 2: Checking if ‘data’ is a JSON object and ‘arrayData’ is a JSON array using ‘instanceof’. Logging the results for verification.
const data = { id: 1, name: "GFG" };
const arrayData = [1, 2, 3];
const isJSONObject = data instanceof Object
&&
!Array
.isArray(data);
const isArrayJSONObject = arrayData instanceof Object && !Array
.isArray(arrayData);
console.log(isJSONObject);
console.log(isArrayJSONObject);
Output
true false