Из структуры прототипа String.isJSON
определение здесь
/**
* String#isJSON() -> Boolean
*
* Check if the string is valid JSON by the use of regular expressions.
* This security method is called internally.
*
* ##### Examples
*
* "something".isJSON();
* // -> false
* "\"something\"".isJSON();
* // -> true
* "{ foo: 42 }".isJSON();
* // -> false
* "{ \"foo\": 42 }".isJSON();
* // -> true
**/
function isJSON() {
var str = this;
if (str.blank()) return false;
str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(str);
}
, поэтому эту версию можно использовать для передачи строкового объекта
function isJSON(str) {
if ( /^\s*$/.test(str) ) return false;
str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(str);
}
function isJSON(str) {
if ( /^\s*$/.test(str) ) return false;
str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(str);
}
console.log ("this is a json", isJSON( "{ \"key\" : 1, \"key2@e\" : \"val\"}" ) )
console.log("this is not a json", isJSON( "{ \"key\" : 1, \"key2@e\" : pippo }" ) )