php - 如何将字符串响应转换为 JSON 对象?

标签 php json curl

我正在使用 curl 调用第三方 API从一个 php 函数。我收到了 JSON 格式的响应(数据类型是字符串)。我想将该响应转换为对象或数组。我试过 json_decode() ,但我收到 null .如果我在浏览器中显示响应并将该字符串响应复制粘贴到 PHP 变量中,我会得到值。所以我无法弄清楚问题是什么。

这是我的代码:

$fullUrl = 'http://example.com/api/assignment/1';
$data = AesCtr::encrypt($data, 'My Key', 256);
$curl = curl_init($fullUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, ['data' => $data]);
$curl_response = curl_exec($curl);
$curl_response = json_decode($curl_response);
echo '<pre>';
print_r($curl_response);

这是回应:
{"identifier":"id", "items":[{"apiResult":"INVALID", "apiResultMessage":"Invalid controls. the field 'resource' is mandatory the field 'type of item' is mandatory the field 'element id' is mandatory the field 'resource' is mandatory", "id":"", "idProject":"", "nameProject":"", "refType":"", "refId":"", "idResource":"", "nameResource":"", "idRole":"", "nameRole":"", "comment":"", "assignedWork":"", "realWork":"", "leftWork":"", "plannedWork":"", "rate":"", "realStartDate":"", "realEndDate":"", "plannedStartDate":"", "plannedEndDate":"", "dailyCost":"", "newDailyCost":"", "assignedCost":"", "realCost":"", "leftCost":"", "plannedCost":"", "idle":"", "billedWork":""}] }

我也试过这个
$curl_response = str_replace("'", "\'", $curl_response);
$curl_response = json_decode($curl_response);

最佳答案

尝试这个:-

$curl_response = curl_exec($curl);

function escapeJsonString($value) { 
    $escapers = array("\'");
    $replacements = array("\\/");
    $result = str_replace($escapers, $replacements, $value);
    return $result;
}



$curl_response = escapeJsonString($curl_response);

$curl_response = json_decode($curl_response,true);

echo '<pre>';print_r($curl_response);

echo $error = json_last_error();

引用文献:- http://www.pontikis.net/tip/?id=5

您发现有用的链接是:- https://stackoverflow.com/a/20845642/4248328

关于php - 如何将字符串响应转换为 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39410506/

相关文章:

php - 使用键模式从 Laravel 4 缓存中删除?

php - MySQLi 不返回获取的数据

javascript - 使用jbuilder访问子对象有很多关系

iphone - 在 iOS 中发布请求?

javascript - curl :如何修复 "Please turn JavaScript on and reload the page"

curl - Nexus 3 - 文件上传到托管 Maven 存储库

php - 提交表单时更新 SESSION 变量

php插入mysql数据库

json - 使用 Golang json.NewDecoder/json.NewEncoder

即使输入正确,Python JSON 模块也会出错