我正在尝试使用Guzzle更新API中的数据。在运行过程中,我遇到了这个Failed to decode json
错误。以下是我所做的:
$client = new Client([
'headers' => [
'Authorization' => 'Bearer ' . env('API_TOKEN'),
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]);
$api_link = env('KINGTIME_API');
$updateAPIlink = $api_link . 'daily-schedules/' . $emp_key . '/' . $date;
$response = $client->put(
$updateAPIlink,
json_decode(json_encode(['form_data' => $tobeUpdated])
), true);
上面的代码返回Failed to decode JSON
错误,并且我的$tobeUpdated
变量中的数据是这样的:
array(8) {
["workPlaceDivisionCode"]=>
string(7) "testeam"
["clockInSchedule"]=>
string(0) "2019-01-01T19:00+09:00"
["clockOutSchedule"]=>
string(0) "2019-01-01T19:00+09:00"
["workFixedStart"]=>
string(22) "2019-01-01T08:00+09:00"
["workFixedEnd"]=>
string(22) "2019-01-01T19:00+09:00"
}
当我尝试在Postman中进行测试时,它会以这种形式接收数据:
{
"workPlaceDivisionCode": "testeam",
"clockInSchedule": "2019-01-01T09:00+09:00",
"clockOutSchedule": "2019-01-01T18:00+09:00",
"workFixedStart": "2019-01-01T08:00+09:00",
"workFixedEnd": "2019-01-01T19:00+09:00"
}
是API本身还是数据馈送中的错误?如果在数据供稿上,如何使用Postman进行日期格式的供稿?这是我第一次使用API。
答案 0 :(得分:0)
我认为您的做法是错误的:
尝试简化代码的这一部分:
$response = $client->put(
$updateAPIlink,
json_decode(json_encode(['form_data' => $tobeUpdated])
), true); //<--Was this "true" suppose to be part of your json_decode or a value to be added to the client?
对此:
$response = $client->put(
$updateAPIlink,
array(
'form_data' => $tobeUpdated
)
);
您从Postman获得的数据为JSON格式。您需要将JSON字符串转换为对象或数组,然后才能访问您的值。
像这样:
echo '<pre>';
$json = ' {
"workPlaceDivisionCode": "testeam",
"clockInSchedule": "2019-01-01T09:00+09:00",
"clockOutSchedule": "2019-01-01T18:00+09:00",
"workFixedStart": "2019-01-01T08:00+09:00",
"workFixedEnd": "2019-01-01T19:00+09:00"
}';
//To get the data as an object:
$object = json_decode($json);
var_dump($object);
echo '<br>';
echo $object->clockInSchedule . '<br><br>';
//To get the data as an array us the "TRUE" flag:
$array = json_decode($json, true);
var_dump($array);
echo '<br>';
echo $array['clockInSchedule'] .'<br><br>';
echo '</pre>';
让我知道是否有帮助。