Background
현재 안정적인 PHP V7.2에서 JSON이 유효하지 않은지 확인하려면 json_last_error() 함수를 사용하여 확인해야 합니다.
>>> json_decode("{"); => null >>> json_last_error(); => 4 >>> json_last_error() === JSON_ERROR_NONE => false >>> json_last_error_msg() => "Syntax error"
예를 들어 Larave에서 여기를 확인하여 확인하세요. JSON 인코딩이 호출된다는 것은 오류를 일으키지 않습니다:
// Once we get the encrypted value we'll go ahead and base64_encode the input // vector and create the MAC for the encrypted value so we can then verify // its authenticity. Then, we'll JSON the data into the "payload" array. $json = json_encode(compact('iv', 'value', 'mac')); if (json_last_error() !== JSON_ERROR_NONE) { throw new EncryptException('Could not encrypt the data.'); } return base64_encode($json);
최소한 JSON 인코딩/디코딩에 오류가 있는지 확인할 수는 있지만 오류 코드와 오류 메시지를 발생시키는 예외를 발생시키는 것에 비하면 약간 투박합니다. .
JSON을 캡처하고 처리할 수 있는 옵션이 이미 있지만 새 버전이 어떤 기능을 훌륭하게 수행할 수 있는지 살펴보겠습니다!
PHP 7.3에서 던지기에 대한 오류 플래그
새로운 옵션 플래그 JSON_THROW_ON_ERROR를 사용하면 try/catch를 사용하도록 이 코드 블록을 다시 작성할 수 있습니다.
다음과 같을 수도 있습니다:
use JsonException; try { $json = json_encode(compact('iv', 'value', 'mac'), JSON_THROW_ON_ERROR); return base64_encode($json); } catch (JsonException $e) { throw new EncryptException('Could not encrypt the data.', 0, $e); }
이 새로운 스타일은 json_last_error() 및 일치 옵션을 검색하는 대신 JSON 데이터를 수신할 때 사용자 코드에 특히 유용하다고 생각합니다. JSON 인코딩 및 디코딩은 오류 핸들러를 활용할 수 있습니다.
이 json_decode() 함수에는 몇 가지 매개변수가 있으며 오류 처리를 활용하려는 경우 PHP 7.3 이하처럼 보일 것입니다.
use JsonException; try { return json_decode($jsonString, $assoc = true, $depth = 512, JSON_THROW_ON_ERROR); } catch (JsonException $e) { // Handle the JSON Exception } // Or even just let it bubble up... /** * Decode a JSON string into an array * * @return array * @throws JsonException */ function decode($jsonString) { return json_decode($jsonString, $assoc = true, $depth = 512, JSON_THROW_ON_ERROR); }
오류 코드 및 오류 메시지 가져오기
이전에 JSON 오류가 발생했습니다. 코드 및 메시지 다음 기능을 사용하세요:
// Error code json_last_error(); // Human-friendly message json_last_error_msg();
새로운 JSON_THROW_ON_ERROR를 사용하는 경우 코드를 사용하고 메시지를 받는 방법은 다음과 같습니다.
try { return json_decode($jsonString, $assoc = true, $depth = 512, JSON_THROW_ON_ERROR); } catch (JsonException $e) { $e->getMessage(); // like json_last_error_msg() $e->getCode(); // like json_last_error() }

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기
