json_decode在有效字符串上返回null吗?

问题描述 投票:0回答:1

嗨,我有一个简单的字符串,称为$response1:

{"SN":"5054494EA805743F","MAC":"CC:19:A8:xx:xx:xx","customerName":"John doe ","id":"6666","serviceID":"1000","jobid":"12345"}

基本上,我是从curl请求中获得此字符串的,但是当我这样做时"$ree = json_decode($response1);print_r($ree);返回null。

这是代码段

                $response1 = curl_exec($ch2);
                $ree = json_decode($response1);
                print_r($dee);  
                print_r($response1);

JSON检查器说字符串可以,并且json_last_error()返回0

这里发生了什么?

php json
1个回答
0
投票

自PHP 7.3起,json_decode函数将接受一个新的JSON_THROW_ON_ERROR选项,该选项将使json_decode引发异常,而不是在出错时返回null。这就是找到问题的方式。

请尝试以下解决方案:

try {  
  $response1 = curl_exec($ch2);
  $ree =json_decode("{", false, 512, JSON_THROW_ON_ERROR);  
}  
catch (\JsonException $exception) {  
  echo $exception->getMessage(); // displays "Syntax error"  
}
© www.soinside.com 2019 - 2024. All rights reserved.