문자열이 JSON인지 여부를 확인하는 정말 빠르고 빠른 방법이 필요합니다. 나는 이것이 최선의 방법이 아니라고 생각합니다.
function isJson($string) {
return ((is_string($string) &&
(is_object(json_decode($string)) ||
is_array(json_decode($string))))) ? true : false;
}
성능 애호가라면이 방법을 개선하고 싶습니까?
답변
function isJson($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
답변
질문에 대한 답변
이 함수 json_last_error
는 JSON 인코딩 및 디코딩 중에 발생한 마지막 오류를 반환합니다. 유효한 JSON을 확인하는 가장 빠른 방법은
// decode the JSON data
// set second parameter boolean TRUE for associative array output.
$result = json_decode($json);
if (json_last_error() === JSON_ERROR_NONE) {
// JSON is valid
}
// OR this is equivalent
if (json_last_error() === 0) {
// JSON is valid
}
참고 json_last_error
PHP에서 지원됩니다> = 5.3.0 만.
정확한 오류를 확인하는 전체 프로그램
개발 시간 동안 정확한 오류를 아는 것이 항상 좋습니다. 다음은 PHP 문서를 기반으로 정확한 오류를 확인하는 전체 프로그램입니다.
function json_validate($string)
{
// decode the JSON data
$result = json_decode($string);
// switch and check possible JSON errors
switch (json_last_error()) {
case JSON_ERROR_NONE:
$error = ''; // 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 UTF-8 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 occured.';
break;
}
if ($error !== '') {
// throw the Exception or exit // or whatever :)
exit($error);
}
// everything is OK
return $result;
}
유효한 JSON INPUT으로 테스트
$json = '[{"user_id":13,"username":"stack"},{"user_id":14,"username":"over"}]';
$output = json_validate($json);
print_r($output);
유효한 출력
Array
(
[0] => stdClass Object
(
[user_id] => 13
[username] => stack
)
[1] => stdClass Object
(
[user_id] => 14
[username] => over
)
)
잘못된 JSON으로 테스트
$json = '{background-color:yellow;color:#000;padding:10px;width:650px;}';
$output = json_validate($json);
print_r($output);
잘못된 출력
Syntax error, malformed JSON.
(PHP> = 5.2 && PHP <5.3.0)에 대한 추가 참고 사항
json_last_error
PHP 5.2에서는 지원되지 않기 때문에 인코딩 또는 디코딩이 boolean을 반환하는지 확인할 수 있습니다 FALSE
. 여기에 예가 있습니다
// decode the JSON data
$result = json_decode($json);
if ($result === FALSE) {
// JSON is invalid
}
이것이 도움이 되길 바랍니다. 행복한 코딩!
답변
당신이 정말로해야 할 일은 이것입니다 …
if (is_object(json_decode($MyJSONArray)))
{
... do something ...
}
이 요청에는 별도의 기능도 필요하지 않습니다. json_decode 주위에 is_object를 감싸고 계속 진행하십시오. 이 솔루션으로 사람들이 너무 많은 생각을하고있는 것 같습니다.
답변
사용 json_decode
“프로브”에 실제로 가장 빠른 방법하지 않을 수 있습니다. 깊게 중첩 된 구조라면 배열의 많은 객체를 인스턴스화하여 버리는 것은 메모리와 시간 낭비입니다.
더 빨리 될 수 있도록 사용 preg_match
과 RFC4627의 정규식 에 또한 유효 기간을 확인 :
// in JS:
var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
text.replace(/"(\\.|[^"\\])*"/g, '')));
PHP에서도 마찬가지입니다 :
return !preg_match('/[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t]/',
preg_replace('/"(\\.|[^"\\\\])*"/', '', $json_string));
그러나 벤치마킹에 신경 쓸만한 성능 애호가는 충분하지 않습니다.
답변
문자열이 json 배열 또는 객체를 나타내는 경우 true 를 반환 합니다 .
function isJson($str) {
$json = json_decode($str);
return $json && $str != $json;
}
기술적으로 유효한 json이지만 숫자, 문자열 또는 부울 만 포함하는 json 문자열을 거부합니다.
var_dump(isJson('{"a":5}')); // bool(true)
var_dump(isJson('[1,2,3]')); // bool(true)
var_dump(isJson('1')); // bool(false)
var_dump(isJson('1.5')); // bool(false)
var_dump(isJson('true')); // bool(false)
var_dump(isJson('false')); // bool(false)
var_dump(isJson('null')); // bool(false)
var_dump(isJson('hello')); // bool(false)
var_dump(isJson('')); // bool(false)
내가 생각해 낼 수있는 가장 짧은 방법입니다.
답변
내가 사용하는 가장 간단하고 빠른 방법은 다음과 같습니다.
$json_array = json_decode( $raw_json , true );
if( $json_array == NULL ) //check if it was invalid json string
die ('Invalid'); // Invalid JSON error
// you can execute some else condition over here in case of valid JSON
입력 한 문자열이 json이 아니거나 유효하지 않은 json이 아닌 경우 json_decode () 가 NULL을 리턴 하기 때문 입니다.
JSON을 검증하는 간단한 기능
여러 곳에서 JSON의 유효성을 검사해야하는 경우 언제든지 다음 기능을 사용할 수 있습니다.
function is_valid_json( $raw_json ){
return ( json_decode( $raw_json , true ) == NULL ) ? false : true ; // Yes! thats it.
}
위 함수에서 유효한 JSON 인 경우 대가로 반환됩니다.
답변
function is_json($str){
return json_decode($str) != null;
}
잘못된 인코딩이 감지되면 http://tr.php.net/manual/en/function.json-decode.php 반환 값이 null입니다.
