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
How to Return Outer HTML of Domdocument
Preparing For Removal of Mcrypt in PHP 7.2
Correct File Permissions For Wordpress
How to Set Http Header to Utf-8 Using PHP Which Is Valid in W3C Validator
How to Find Out If You'Re Using Https Without $_Server['Https']
How to Refresh Token With Google API Client
How to Select and Upload Multiple Files With HTML and PHP, Using Http Post
Why Would Json_Encode Return an Empty String
What's the Maximum Value For an Int in PHP
Turning Multidimensional Array into One-Dimensional Array
Base_Url() Function Not Working in Codeigniter
What Is the Best Method to Merge Two PHP Objects
Curl and PHP - How to Pass a Json Through Curl by Put,Post,Get
Post an Array from an HTML Form Without JavaScript
How to Get Directory Size in PHP
Convert Dot Syntax Like "This.That.Other" to Multi-Dimensional Array in PHP