【问题标题】:How to convert string response into JSON object?如何将字符串响应转换为 JSON 对象?
【发布时间】:2017-01-17 12:59:48
【问题描述】:

我正在使用 php 函数中的 curl 调用第三方 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-parser.com/a7826645 尝试使用json_last_error_msg() 检查 JSON 解码错误消息
  • 请不要随意在问题的部分加粗,这样会更难阅读。
  • @Anant,我已经回复了问题。
  • @AlokPatel,我知道 JSON 是有效的。但我的问题是那为什么我不能解码呢?
  • @Anant,是的,这就是响应。但请记住,它是字符串数据类型。这里看起来像对象,因为我从浏览器复制/粘贴。

标签: php json curl


【解决方案1】:

试试这个:-

$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

【讨论】:

  • 问题已解决。我从here 得到了解决方案。见评论the most common part
【解决方案2】:

尝试添加第二个参数“assoc”以获取数组到 json_decode 函数:

$curl_response = json_decode($curl_response, true);

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2022-11-19
    • 2011-08-19
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多