문제

누구든지 PHP에 대한 강력한 (및 방탄) IS_JSON 기능 스 니펫을 아는 사람이 있습니까? 나는 (분명히) 문자열이 JSON인지 아닌지 알아야 할 상황이 있습니다.

흠, 아마도 a를 통과 할 것입니다 jsonlint 요청/응답이지만 약간 과잉으로 보입니다.

도움이 되었습니까?

해결책

내장을 사용하는 경우 json_decode PHP 함수, json_last_error 마지막 오류를 반환합니다 (예 : JSON_ERROR_SYNTAX 당신의 줄이 JSON이 아니었을 때).

대개 json_decode 보고 null 그래도.

다른 팁

사용은 어떻습니까 json_decode, 반환해야합니다 null 주어진 문자열이 유효하지 않은 경우 JSON 인코딩 된 데이터?

매뉴얼 페이지의 예 3을 참조하십시오.

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes
// single quotes are not valid 
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null

// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null

내 프로젝트의 경우이 기능을 사용합니다 (읽어주세요.메모"에 json_decode () 문서).

JSON_DECODE ()로 전달하는 동일한 인수를 전달합니다. 특정 응용 프로그램 "오류"(예 : 깊이 오류)를 감지 할 수 있습니다.

php> = 5.6

// PHP >= 5.6
function is_JSON(...$args) {
    json_decode(...$args);
    return (json_last_error()===JSON_ERROR_NONE);
}

php> = 5.3

// PHP >= 5.3
function is_JSON() {
    call_user_func_array('json_decode',func_get_args());
    return (json_last_error()===JSON_ERROR_NONE);
}

사용 예 :

$mystring = '{"param":"value"}';
if (is_JSON($mystring)) {
    echo "Valid JSON string";
} else {
    $error = json_last_error_msg();
    echo "Not valid JSON string ($error)";
}

그렇지 않습니다 json_decode() a json_last_error() 당신을 위해 일합니까? "이것은 JSON처럼 보이거나 실제로 검증하는 방법을 찾고 있습니까? json_decode() PHP 내에서 효과적으로 검증하는 유일한 방법이 될 것입니다.

$this->post_data = json_decode( stripslashes( $post_data ) );
  if( $this->post_data === NULL )
   {
   die( '{"status":false,"msg":"The post_data parameter must be valid JSON"}' );
   }

이것은 최고이고 효율적인 방법입니다

function isJson($string) {
    return (json_decode($string) == null) ? false : true;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top