반응형
문자열이 유효한 JSON인지 확인하는 방법
PHP용 is_JSON 함수 스니펫에 대해 아시는 분?문자열이 JSON인지 아닌지를 알 필요가 있는 상황입니다.
음, 아마 JSONLint 요청/응답으로 실행했을지도 모르지만, 그건 좀 지나친 것 같아요.
빌트인 PHP 함수를 사용하는 경우 마지막 오류(예를 들어 문자열이 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)";
}
를 사용하는 것은 어떨까요?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
Doesn't.json_decode()
와 함께json_last_error()
도움이 될까요?"이것이 JSON처럼 보이나"라고 말하는 방법만 찾으시는지 아니면 실제로 검증하는 방법을 찾으시는지요? json_decode()
PHP 내에서 효과적으로 검증할 수 있는 유일한 방법입니다.
이것이 최선이며 효율적인 방법이다.
function isJson($string) {
return (json_decode($string) == null) ? false : true;
}
$this->post_data = json_slashs ( stripslashs ( $post_data ) ;if ( $ this - > post _ data === NULL ){die ( ' { " status " : false , msg " ) :post_data 파라미터는 유효한 JSON"}'이어야 합니다.}
json_validate()는 PHP 8.3으로 동작합니다.
언급URL : https://stackoverflow.com/questions/1187576/how-to-determine-whether-a-string-is-valid-json
반응형
'source' 카테고리의 다른 글
React.useMemo를 사용한 비동기 호출 (0) | 2023.03.20 |
---|---|
워드프레스:기본 메뉴 항목에 URL GET 매개 변수를 추가하려면 어떻게 해야 합니까? (0) | 2023.03.20 |
파워 쿼리를 사용하여 뛰어난 성능을 발휘하는 Json (0) | 2023.03.20 |
각진 '='의 의미는 무엇입니까?JS 지시 격리 범위 선언? (0) | 2023.03.20 |
Typescript 인터페이스 기본값 (0) | 2023.03.20 |