Test if a value is a parseable JSON string.
var isJSON = require( '@stdlib/utils/is-json' );
Tests if a value
is a parseable JSON string
.
var value = '{"a":5}';
var bool = isJSON( value );
// returns true
- validates that the input
value
is astring
literal. For all other inputs, the method returnsfalse
. - validates that a
string
begins with either[
or{
and ends with a corresponding]
or}
, respectively. Hence, the method will returnfalse
for the followingstrings
, despiteJSON.parse
accepting their input: -'<number>'
; e.g.,'5'
-'<boolean>'
; e.g.,'true'
-'null'
- uses
JSON.parse
inside atry/catch
. Hence, this method cannot be optimized by the compiler during runtime. Nevertheless, using thisfunction
is better than embedding atry/catch
within a largerfunction
which could be optimized in the absence of atry/catch
.
var isJSON = require( '@stdlib/utils/is-json' );
console.log( isJSON( '{"a":5}' ) );
// returns true
console.log( isJSON( '{a":5}' ) );
// returns false