Socrates Socrates - 1 year ago 95
JSON Question

PHP7, JSON and Zend (decoding failed: syntax error)

I recently upgraded to PHP 7.0.4 and nginx 1.8.1, my application uses the Zend Framework (Magento Since that upgrade, our customers sometimes get an "Decoding failed: Syntax error" when submitting an orderm which is thrown in

public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY)
$encodedValue = (string) $encodedValue;
if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
$decode = json_decode($encodedValue, $objectDecodeType);

// php < 5.3
if (!function_exists('json_last_error')) {
if (strtolower($encodedValue) === 'null') {
return null;
} elseif ($decode === null) {
#require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Decoding failed');
// php >= 5.3
} elseif (($jsonLastErr = json_last_error()) != JSON_ERROR_NONE) {
#require_once 'Zend/Json/Exception.php';
switch ($jsonLastErr) {
throw new Zend_Json_Exception('Decoding failed: Maximum stack depth exceeded');
throw new Zend_Json_Exception('Decoding failed: Unexpected control character found');
throw new Zend_Json_Exception('Decoding failed: Syntax error');
throw new Zend_Json_Exception('Decoding failed');

return $decode;

I read about a bug that PHP7 and JSON decode behaves differently when encoding an empty string. Does anyone know if this bug is related to PHP7 or to my application/server?


Answer Source

This is an absolutely normal behaviour of json_decode.

It will throw this exception if the given string is not a valid JSON String.

As you already mentioned, an empty string is also not a valid JSON String.

json_decode('Hello') // invalid
json_decode("Hello") //invalid


json_decode("'Hello'") // valid JSON string

Empty strings will raise an exception since PHP7!

"Calling json_decode with 1st argument equal to empty PHP string or value that after casting to string is empty string (NULL, FALSE) results in JSON syntax error."

So... to answer your question: In my opinion, your application has the problem you need to solve, if downgrading your PHP version is not an option.

The Magenta function needs to check for a valid representation of a JSON string BEFORE passing it to the json_decode function.

Try to set the variable to "" or {} if it is not a string (is_string) or if it is empty.

If this is not the problem, it might be possible that your string is not encoded as it should be. Many times encoding of the strings passed to json_decode will result into that exception also.