Проверяем является ли строка JSON строкой
Код ниже проверяет переданную строку, является ли она JSON строкой. Декодирует её если передана JSON строка.
/** * Decodes JSON string only if specified string is really JSON, otherwise return false. * * Based on {@see https://stackoverflow.com/questions/6041741/fastest-way-to-check-if-a-string-is-json-in-php} * * @param string|int $string String to check and decode. * @param int $flags json_decode() fourth parameter. {@see https://www.php.net/manual/en/function.json-decode.php} * * @return false|string JSON data if a JSON string was passed. `false` if it is not a JSON string. */ function maybe_json( $string, $flags = 0 ){ if( ! is_string( $string ) ) return false; $json = json_decode( $string, null, 512, $flags ); if( json_last_error() !== JSON_ERROR_NONE ) return false; if( $json === $string ) return false; return $json; }