Warning: For methods relying on JSON.parse
- Arrays and quote surrounded strings will pass too (ie. console.log(JSON.parse('[3]'), JSON.parse('"\uD800"'))
)
To avoid all non-object JSON primitives (boolean, null, array, number, string), I suggest using the following:
/* Validate a possible object ie. o = { "a": 2 } */
const isJSONObject = (o) =>
!!o && (typeof o === 'object') && !Array.isArray(o) &&
(() => { try { return Boolean(JSON.stringify(o)); } catch { return false } })()
/* Validate a possible JSON object represented as string ie. s = '{ "a": 3 }' */
function isJSONObjectString(s) {
try {
const o = JSON.parse(s);
return !!o && (typeof o === 'object') && !Array.isArray(o)
} catch {
return false
}
}
Code Explanation
- !!o - Not falsy (excludes null, which registers as typeof 'object')
- (typeof o === 'object') - Excludes boolean, number, and string
- !Array.isArray(o) - Exclude arrays (which register as typeof 'object')
- try ... JSON.stringify / JSON.parse - Asks JavaScript engine to determine if valid JSON
Why not use the hasJsonStructure() answer?
Relying on toString()
is not a good idea. This is because different JavaScript Engines may return a different string representation. In general, methods which rely on this may fail in different environments or may be subject to fail later should the engine ever change the string result
Why is catching an exception not a hack?
It was brought up that catching an exception to determine something's validity is never the right way to go. This is generally good advice, but not always. In this case, exception catching is likely is the best route because it relies on the JavaScript engine's implementation of validating JSON data.
Relying on the JS engine offers the following advantages:
- More thorough and continually up-to-date as JSON spec changes
- Likely to run faster (as it's lower level code)
When given the opportunity to lean on the JavaScript engine, I'd suggest doing it. Particularly so in this case. Although it may feel hacky to catch an exception, you're really just handling two possible return states from an external method.