PHP8.3要有新函數了! (json_validate函數說明)

藏色散人
發布: 2023-04-11 09:58:01
轉載
2092 人瀏覽過

這篇文章為大家帶來了關於php8.3的最新相關信息,其中主要介紹了PHP8.3將會添加名為json_validate的函數,那麼這個函數有什麼用呢?怎麼使用它呢?下面一起來看一下,希望對大家有幫助。

PHP8.3要有新函數了! (json_validate函數說明)

PHP 8.3 前瞻:`json_validate` 函數

PHP 8.3 將會新增名為json_validate 的函數,用來驗證傳入的字串是否是合法的JSON 字串。

在目前,驗證 JSON 字串的一種通用做法是嘗試將其解碼,並透過捕獲異常來確定。但在某些情況下我們可能並不需要取得具體的內容,只需要驗證其合法。新的 json_validate 函數相比 json_decode 耗用的記憶體和資源更少,因為它只分析字串而不會嘗試解碼。

函數簽章

/**
 * 验证传入的字符串是否为合法 JSON 字符串
 *
 * @param string $json 准备验证的字符串
 * @param int $depth 最大嵌套深度,必须大于 0
 * @param int $flags 标志掩码,用于指定行为
 * @return bool $json 是合法 JSON 字符串时返回 true,否则返回 false
 */
function json_validate(string $json, int $depth = 512, int $flags = 0): bool {}
登入後複製

標誌Flags

json_validate 的第三個參數是flags,用來指定函數的行為。在目前,唯一可用的標誌是 JSON_INVALID_UTF8_IGNORE。

該標誌在 PHP 7.2 中添加,作為 json_decode 的標誌常數,用於忽略對應字串中的 UTF-8 字元。

json_validate('[1, 2, 3]', flags: JSON_INVALID_UTF8_IGNORE); // true

json_validate("[\"\xc1\xc1\",\"a\"]"); // false
json_validate("[\"\xc1\xc1\",\"a\"]", flags: JSON_INVALID_UTF8_IGNORE); // true
登入後複製

錯誤處理

json_validate 本身不會回傳錯誤碼,如果你想要取得特定的錯誤訊息,可用使用 json_last_error 和 json_last_error_msg 取得。

json_validate(""); // false

json_last_error(); // 4
json_last_error_msg(); // "Syntax error"
登入後複製
json_validate("null"); // true

json_last_error(); // 0
json_last_error_msg(); // "No error"
登入後複製

範例

驗證字串並拋出異常

if (json_validate($_GET['json']) === false) {
    throw new \JsonException(json_last_error_msg(), json_last_error());
}
登入後複製

#取代先前的驗證方式

- $value = json_decode($_GET['json'], flags: JSON_THROW_ON_ERROR);
+ if (!json_validate($_GET['json'])) {
+   throw new \JsonException(json_last_error_msg(), json_last_error());
+ }
+ $value = json_decode($_GET['json']);
登入後複製

Polyfill 搶先適配

如果你想提前為PHP 8.3 做適配,以在8.3 發布的第一時間無縫切換到json_validate,你可以手動定義一個函數,以在先前的版本中模仿json_validate 的作用。

if (!function_exists('json_validate')) {  
  function json_validate(string $json, int $depth = 512, int $flags = 0): bool {  
  if ($flags !== 0 && $flags !== \JSON_INVALID_UTF8_IGNORE) {  
  throw new \ValueError('json_validate(): Argument #3 ($flags) must be a valid flag (allowed flags: JSON_INVALID_UTF8_IGNORE)');  
  }  
  if ($depth <= 0 ) {  
  throw new \ValueError(&#39;json_validate(): Argument #2 ($depth) must be greater than 0&#39;);  
  }  
  \json_decode($json, null, $depth, $flags);  
  return \json_last_error() === \JSON_ERROR_NONE;  
  }  
}
登入後複製

由於此函數內部依然使用 json_decode,所以其實際上並沒有效能上的改進,只是提供了和 json_validate 相似的介面。

推薦學習:《PHP影片教學

以上是PHP8.3要有新函數了! (json_validate函數說明)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:learnku.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!