How to check if an object is a JSON object in Javascript

Marika Lam
1 min readOct 17, 2022

Answer

Use the constructor attribute to check if an object is a JSON object in Javascript.

Code

var testingObject = {};if (testingObject && testingObject.constructor === ({}).constructor) {
console.log("It's a JSON object!");
} else {
console.log("It's NOT a JSON object!");
}

Explanation

First make sure that that the object is not null. Then check the constructor of testingObject with the constructor of an empty JSON object. If the constructors are the same, print out "It's a JSON object!". If the constructors are not the same, print out "It's NOT a JSON object!".

Use this constructor check before you use any JSON functions such as Object.keys(testingObject).

Become a member on Medium!

Amazon Links to “Must-Haves” as a WFH Software Engineer 🙂💻

24-inch budget-friendly monitor, Portable monitor, Laptop stand, Waterproof desk mat, Keyboard cleaning gel, Six-outlet wall charger and surge protector,, Wi-Fi extender, Blue-light–blocking glasses, Memory foam gel pad, Foam footrest

Courses to learn more about datastructures/algorithms ✍️

Stanford, Duke, UCSD

Courses to learn more about databases 👓

DB Foundations, Data Scientists specialization

Courses to learn more about React 🧢

Full-Stack WebDev, Front-End WebDev with React, IBM Full Stack

--

--