Fastest Way to Check If a String Is Json in PHP

How to determine whether a string is valid JSON?

If you are using the built in json_decode PHP function, json_last_error returns the last error (e.g. JSON_ERROR_SYNTAX when your string wasn't JSON).

Usually json_decode returns null anyway.

How to check if a string is a valid JSON string?

A comment first. The question was about not using try/catch.

If you do not mind to use it, read the answer below.
Here we just check a JSON string using a regexp, and it will work in most cases, not all cases.

Have a look around the line 450 in https://github.com/douglascrockford/JSON-js/blob/master/json2.js

There is a regexp that check for a valid JSON, something like:

if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

//the json is ok

}else{

//the json is not ok

}

EDIT: The new version of json2.js makes a more advanced parsing than above, but still based on a regexp replace ( from the comment of @Mrchief )

How to test if a string is JSON or not?

Use JSON.parse

function isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}

How to validate JSON in PHP older than 5.3.0?

$ob = json_decode($json);
if($ob === null) {
// $ob is null because the json cannot be decoded
}


Related Topics



Leave a reply



Submit