首页 > 解决方案 > json_decode 在有效的 json 上给出 null

问题描述

我的 $result 中有这个文本

{"meta":{"code":400,"message":"Bad Request"},"error":"userId is required.","extras":null}

但是当我这样做时

$json_result = json_decode($result, true);
print_r($json_result);

它给了我null。我已经在任何地方验证了这个文本,它说它是一个有效的 json。

编辑

这是我的代码

<?php

$data = "&userId=";
$data_string = $data;
$url = 'http://apptellect.cloudapp.net/binance/api/v1/get_user_assets/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo $result = curl_exec($ch);
echo '<hr>';
curl_close($ch);
$json_result = json_decode($result, true);
echo json_last_error_msg();
echo '<hr>';
//$json_result = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $result), true );
print_r($json_result);
?>

标签: phpjsoncurl

解决方案


我已经解决了这个问题请检查下面的代码

<?php
// Your code here!
$data = "&userId=";
$data_string = $data;
$url = 'http://apptellect.cloudapp.net/binance/api/v1/get_user_assets/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo $result = curl_exec($ch);
echo '<hr>';
curl_close($ch);

// This will remove unwanted characters.
// Check http://www.php.net/chr for details
for ($i = 0; $i <= 31; ++$i) { 
    $result = str_replace(chr($i), "", $result); 
}
$result = str_replace(chr(127), "", $result);

// This is the most common part
// Some file begins with 'efbbbf' to mark the beginning of the file. (binary level)
// here we detect it and we remove it, basically it's the first 3 characters 
if (0 === strpos(bin2hex($result), 'efbbbf')) {
   $result = substr($result, 3);
}

$json_result =    json_decode($result, true);

echo json_last_error_msg();
echo '<hr>';
print_r($json_result);

?>

我确定它工作正常,请检查

Curl 发送了 json 响应。它显示正确的 json,但它有不需要的字符。我们已经删除了不需要的字符二进制级别。然后传递给 json_decode 函数

快乐编程

谢谢,作为


推荐阅读