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

4

我正在使用 curl 在一个 PHP 函数中调用第三方 API。我得到了一个 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);

JSON字符串似乎有效,可以尝试使用json_last_error_msg()检查JSON解码错误消息。请访问http://json-parser.com/a7826645。 - Alok Patel
请不要随意加粗你的问题中的部分内容,这会使阅读变得更加困难。 - T.J. Crowder
@Anant,我已经在问题中展示了回应。 - Akshay Vaghasiya
@AlokPatel,我知道JSON是有效的。但我的问题是为什么我无法解码它? - Akshay Vaghasiya
@AkshayVaghasiya 使用json_last_error_msg()检查错误消息。 - Alok Patel
显示剩余3条评论
2个回答

3
尝试这个:-
$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://dev59.com/6WQm5IYBdhLWcg3w8Sre#20845642


问题解决了。我从这里得到了解决方案。请查看评论“最常见部分”。 - Akshay Vaghasiya

1
尝试为json_decode函数添加第二个参数"assoc",以获取数组:

$curl_response = json_decode($curl_response, true);

希望这能有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接