PHP 5.3+ 提供 json_last_error() 可精確判斷解碼錯誤,舊版本需靠 json_decode() 回傳 null 判斷(但 null 本身也是合法 JSON)。本文整理三種常見場景的判斷函數。
function is_json($string) {
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
function is_not_json($str) {
return is_null(json_decode($str));
}
// 注意:輸入 'null' 會回傳 false(因為 null 是合法 JSON)
function analyJson($json_str) {
$json_str = str_replace('\\\\', '', $json_str); // 移除雙重轉義
$out = [];
if (preg_match('/\{.*\}/s', $json_str, $out)) {
return json_decode($out[0], true);
}
return false;
}
| 常數 | 說明 |
|---|---|
| JSON_ERROR_NONE | 無錯誤 |
| JSON_ERROR_DEPTH | 超過最大堆疊深度 |
| JSON_ERROR_STATE_MISMATCH | 語法錯誤(如缺逗號、括號不匹配) |
| JSON_ERROR_CTRL_CHAR | 控制字元錯誤 |
| JSON_ERROR_SYNTAX | 語法錯誤 |
| JSON_ERROR_UTF8 | UTF-8 編碼錯誤(輸入必須為 UTF-8) |
json_encode/decode **只接受 UTF-8 編碼**,非 UTF-8 輸入必須先 iconv/mb_convert_encoding 轉碼json_decode($str, true) 回傳關聯陣列,預設回傳 stdClass 物件