php - 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);
?>
解决方案
我已经解决了这个问题请检查下面的代码
<?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 函数
快乐编程
谢谢,作为
推荐阅读
- javascript - react.js 如何在触发某些操作时重新渲染 App.js
- python - 如何在 Python 中使用 C API 获取对象 ID?
- python - 在已激活 WSL 的 Windows 下安装 Anaconda 2020.02 失败
- javascript - Node.js 不转发到服务器上的“Google Drive Login”,但在 localhost 上工作
- json - jq:数据非规范化
- python - 计算机视觉,重叠块以解决最终图像的连续性
- matlab - Matlab GUI 绘制区域大小规范
- python - 如何通过气流在 s3 中运行 python 脚本
- python - ACF 时间序列:ValueError:操作数无法与形状一起广播
- python - TypeError:kollision() 缺少 1 个必需的位置参数:'self'