Something like:
var jsonString = \'{ \"Id\": 1, \"Name\": \"Coke\" }\';
//should be true
IsJsonString(jsonString);
//should be false
IsJsonString(\"foo\");
From Prototype framework String.isJSON
definition here
/**
* 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);
}
so this is the version that can be used passing a string object
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 }" ) )
I used a really simple method to check a string how it's a valid JSON or not.
function testJSON(text){
if (typeof text!=="string"){
return false;
}
try{
JSON.parse(text);
return true;
}
catch (error){
return false;
}
}
Result with a valid JSON string:
var input='["foo","bar",{"foo":"bar"}]';
testJSON(input); // returns true;
Result with a simple string;
var input='This is not a JSON string.';
testJSON(input); // returns false;
Result with an object:
var input={};
testJSON(input); // returns false;
Result with null input:
var input=null;
testJSON(input); // returns false;
The last one returns false because the type of null variables is object.
This works everytime. :)
Here is the typescript version too:
JSONTryParse(input: any) {
try {
//check if the string exists
if (input) {
var o = JSON.parse(input);
//validate the result too
if (o && o.constructor === Object) {
return o;
}
}
}
catch (e: any) {
}
return false;
};
Oh you can definitely use try catch to check whether its or not a valid JSON
Tested on Firfox Quantom 60.0.1
use function inside a function to get the JSON tested and use that output to validate the string. hears an example.
function myfunction(text){
//function for validating json string
function testJSON(text){
try{
if (typeof text!=="string"){
return false;
}else{
JSON.parse(text);
return true;
}
}
catch (error){
return false;
}
}
//content of your real function
if(testJSON(text)){
console.log("json");
}else{
console.log("not json");
}
}
//use it as a normal function
myfunction('{"name":"kasun","age":10}')
In prototypeJS, we have method isJSON. You can try that. Even json might help.
"something".isJSON();
// -> false
"\"something\"".isJSON();
// -> true
"{ foo: 42 }".isJSON();
// -> false
"{ \"foo\": 42 }".isJSON();
I think I know why you want to avoid that. But maybe try & catch !== try & catch. ;o) This came into my mind:
var json_verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};
So you may also dirty clip to the JSON object, like:
JSON.verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};
As this as encapsuled as possible, it may not break on error.