Skip to content

Instantly share code, notes, and snippets.

@Traineratwot
Created January 18, 2022 07:40
Show Gist options
  • Save Traineratwot/240317a8bef043eb825c333cb637edfc to your computer and use it in GitHub Desktop.
Save Traineratwot/240317a8bef043eb825c333cb637edfc to your computer and use it in GitHub Desktop.
проверяте является ли строка json tckb да возвращяет json как объект или массив
<?
function jsonValidate($string, $assoc = TRUE, $depth = 1024)
{
try {
if (!is_string($string)) {
return $string;
}
$error = 0;
// decode the JSON data
$string = preg_replace('/[[:cntrl:]]/', '', $string);
if (defined('JSON_THROW_ON_ERROR')) {
$result = json_decode($string, (bool)$assoc, $depth, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
} else {
$result = json_decode($string, (bool)$assoc, $depth, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}
// switch and check possible JSON errors
switch (json_last_error()) {
case JSON_ERROR_NONE:
$error = 0; // JSON is valid // No error has occurred
break;
case JSON_ERROR_DEPTH:
$error = 'The maximum stack depth has been exceeded.';
break;
case JSON_ERROR_STATE_MISMATCH:
$error = 'Invalid or malformed JSON.';
break;
case JSON_ERROR_CTRL_CHAR:
$error = 'Control character error, possibly incorrectly encoded.';
break;
case JSON_ERROR_SYNTAX:
$error = 'Syntax error, malformed JSON.';
break;
// PHP >= 5.3.3
case JSON_ERROR_UTF8:
$error = 'Malformed utf8 characters, possibly incorrectly encoded.';
break;
// PHP >= 5.5.0
case JSON_ERROR_RECURSION:
$error = 'One or more recursive references in the value to be encoded.';
break;
// PHP >= 5.5.0
case JSON_ERROR_INF_OR_NAN:
$error = 'One or more NAN or INF values in the value to be encoded.';
break;
case JSON_ERROR_UNSUPPORTED_TYPE:
$error = 'A value of a type that cannot be encoded was given.';
break;
default:
$error = 'Unknown JSON error occurred.';
break;
}
if ($error) {
throw new Exception($error);
}
} catch (Exception $e) {
throw new Exception($e->getMessage(), $e->getCode(), $e);
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment