I'm receiving a json array from php as the return of curl_exec in PHP (first json PHP -> python, that returns another json), and decode fails due to bad syntax.
The piece of API code:
if($_GET['url'] == 'tomorrowdate'){
$tomorrow = date('Y-m-d', strtotime(' + 1 days'));
$risposta = [
"tomorrow" => $tomorrow
];
echo json_encode($risposta);
http_response_code(200);
}
the curl code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
//var_dump($output);
$data = stripslashes($data);
$json_array = json_decode($output, true);
//var_dump(curl_error($ch));
curl_close($ch);
var_dump($json_array);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
I tried to adapt your code with mine but the problem remains ...
function remove_utf8_bom($text){
$bom = pack('H*','EFBBBF');
$text = preg_replace("/^$bom/", '', $text);
return $text;
}
$tomorrow = date('Y-m-d', strtotime(' + 1 days'));
$risposta = [
"tomorrow" => $tomorrow
];
$json = remove_utf8_bom($risposta);
echo json_encode($json);
var_dump(json_decode($json_encode, TRUE));
The output is:
{"tomorrow":"2018-09-15"}NULL - Syntax error, malformed JSON
Copyright Notice:Content Author:「Manu Blackwell」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/52337698/problem-with-json-decode-syntax-error-malformed-json