How to validate JSON in PHP
Snippet
The function json_last_error returns the last error occurred during the JSON encoding and decoding.
<?php
function isJSON($string) {
if(is_array($string)) return false;
if(!empty($string)){
if($string == '{}') return true;
json_decode($string);
if(json_last_error() === JSON_ERROR_NONE) return true;
}
return false;
}
$json = '{"website":{"domain":"wtools.io","title":"Online Web Tools"}}';
if(isJSON($json)){
echo "Valid JSON string";
} else {
echo "Not valid JSON string";
}
But a better way is a function that returns an array or false if JSON is not valid (To avoid call the json_decode function 2 times):
<?php
function isJSON($string) {
if(!empty($string) && !is_array($string)){
if($string == '{}') return [];
$res = json_decode($string, true);
if(json_last_error() === JSON_ERROR_NONE) return $res;
}
return false;
}
$json = '{"website":{"domain":"wtools.io","title":"Online Web Tools"}}';
$data = isJSON($json);
if($data!==false){
print_r($data);
} else {
echo "Not valid JSON string";
}
If you want to validate JSON online, then you can use our free tool.