How to check if an incoming param to my function is an proper object in javascript?
code
function abc(object1, data1) {
if(i need to verify here object1 is a proper JSON then only it should proceed) {
//do the operation
}
}
How to check if an incoming param to my function is an proper object in javascript?
code
function abc(object1, data1) {
if(i need to verify here object1 is a proper JSON then only it should proceed) {
//do the operation
}
}
The function below can be used to check if provided data is a valid JSON, for an object (string
, boolean
, ...) it will return false
:
const isJson = (data) => {
try {
return Boolean(JSON.parse(data));
} catch {
return false
}
}
function abc(object1, data1) {
let isJson;
try {
JSON.parse(object1);
isJson = true;
} catch (ignore) {}
if (isJson) {
//do the operation
console.log("object1 - " + object1 + " - is json-parseable");
return;
}
console.log("object1 - " + object1 + " - is not json-parseable");
}
// test
abc("null"); // object1 - null - is json-parseable
abc("{\"aa\":\"bb\"}"); // object1 - {"aa":"bb"} - is json-parseable
abc(undefined); // object1 - undefined - is not json-parseable
abc("syntax error"); // object1 - syntax error - is not json-parseable