Проверяем является ли строка JSON строкой
Код ниже проверяет переданную строку, является ли она JSON строкой. Декодирует её если передана JSON строка.
Аналог maybe_unserialize(), только для JSON данных.
/**
* Decodes JSON string only if specified string is really JSON,
* otherwise return original passed data.
*
* Based on {@see https://stackoverflow.com/questions/6041741/fastest-way-to-check-if-a-string-is-json-in-php}
*
* @param mixed $data String to check and decode.
* @param int $flags json_decode() fourth parameter. {@see https://php.net/json_decode}
*
* @return mixed JSON data if a JSON string is passed. Original passed data if it is not a JSON string.
*/
function maybe_json_decode( $data, $flags = 0 ){
if( ! is_string( $data ) ){
return $data;
}
$data = trim( $data );
$json = json_decode( $data, null, 512, $flags );
if( json_last_error() !== JSON_ERROR_NONE ){
return $data;
}
if( $json === $data ){
return $data;
}
return $json;
}
Usage example:
$tests = [
'{ "asd": 123 }',
12,
' 123',
'[ 123 ]',
'{foo}',
];
foreach( $tests as $data ){
var_dump( maybe_json_decode( $data ) );
}
/*
object(stdClass)#1301 (1) {
["asd"]=>
int(123)
}
int(12)
int(123)
array(1) {
[0]=>
int(123)
}
string(5) "{foo}"
*/