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


How to convert string response into JSON object?

我正在使用curl从php函数调用第三方api。我得到一个JSON格式的响应(数据类型是字符串)。我想把那个响应转换成对象或数组。我试过json_decode(),但我得到的是null。如果我在浏览器中显示response并复制粘贴该字符串response到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

尝试添加第二个参数"assoc"来获取数组到json_decode函数:

$curl_response = json_decode($curl_response, true);

希望对你有帮助。