Created
May 29, 2023 19:50
-
-
Save mark05e/2b8e23a999c69f558236ecf0d2017cd4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Checks if a given input is a valid JSON string or an object. | |
* | |
* @param {string|object} input - The input to be checked, which can be a JSON string or an object. | |
* @returns {boolean} - Returns true if the input is a valid JSON string or an object, false otherwise. | |
*/ | |
function isJSON(input) { | |
// Check if the input is not a string | |
if (typeof input !== 'string') { | |
// Check if the input is already an object | |
if (typeof input === 'object' && input !== null) { | |
return true; | |
} | |
return false; | |
} | |
try { | |
// Try parsing the input string as JSON | |
const obj = JSON.parse(input); | |
if (typeof obj === 'object' && obj !== null) { | |
return true; | |
} | |
return false; | |
} catch (err) { | |
// If parsing fails, input is not a valid JSON string | |
return false; | |
} | |
} | |
function isJSON_test() { | |
const myObj = { name: 'John', age: 30 }; | |
const myJSON = JSON.stringify(myObj); | |
console.log(isJSON(myObj)); // true | |
console.log(isJSON(myJSON)); // true | |
console.log(isJSON('not JSON')); // false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment