如何通过try和catch处理json解码的错误

vin*_*eet 14 php

我无法处理json解码错误.我在下面提到我的代码: -

try{
 $jsonData=file_get_contents($filePath). ']';
 $jsonObj = json_decode($jsonData, true);
}  catch(Exception $e){
  echo '{"result":"FALSE","message":"Caught exception: '. 
     $e->getMessage().' ~'.$filePath.'"}';
}
Run Code Online (Sandbox Code Playgroud)

我是新的php程序员.对不起,如果出了什么问题.

小智 20

另一种处理json解码错误的方法: -

if ($jsonObj === null && json_last_error() !== JSON_ERROR_NONE) {
   echo "json data is incorrect";
}
Run Code Online (Sandbox Code Playgroud)


ser*_*gej 7

自 PHP 7.3 起可以使用JSON_THROW_ON_ERROR常量。

try {
    $jsonObj = json_decode($jsonData, true, $depth=512, JSON_THROW_ON_ERROR);
} catch (Exception $e) {
    // handle exception
}
Run Code Online (Sandbox Code Playgroud)

更多:https : //www.php.net/manual/de/function.json-decode.php#refsect1-function.json-decode-changelog


Ver*_*e89 5

发生错误时,例如没有有效的json或超出深度大小,json_decode返回null。因此,基本上,您只需要检查所获取的jsondata是否为null。如果是这样,请使用json_last_error查看出了什么问题,否则请继续执行脚本。

$json_data = json_decode($source, true);

if($json_data == null){
  echo json_last_error() . "<br>";
  echo $source; // good to check what the source was, to see where it went wrong
}else{
  //continue with script
}
Run Code Online (Sandbox Code Playgroud)

这样的事情应该起作用。


Dim*_*rab 5

也许你可以尝试,验证 json_decode

try {
  $jsonData = file_get_contents($filePath) . ']';
  $jsonObj  = json_decode($jsonData, true);

  if (is_null($jsonObj)) {
    throw ('Error');
  }
} catch (Exception $e) {
  echo '{"result":"FALSE","message":"Caught exception: ' . 
    $e->getMessage() . ' ~' . $filePath . '"}';
}
Run Code Online (Sandbox Code Playgroud)

也读这个

  • 当您只需要检查$ jsonObj === null时为什么要调用is_null()? (2认同)