Php json decode json error syntax

json_decode

Takes a JSON encoded string and converts it into a PHP value.

Parameters

The json string being decoded.

This function only works with UTF-8 encoded strings.

Note:

PHP implements a superset of JSON as specified in the original » RFC 7159.

When true , JSON objects will be returned as associative array s; when false , JSON objects will be returned as object s. When null , JSON objects will be returned as associative array s or object s depending on whether JSON_OBJECT_AS_ARRAY is set in the flags .

Maximum nesting depth of the structure being decoded. The value must be greater than 0 , and less than or equal to 2147483647 .

Bitmask of JSON_BIGINT_AS_STRING , JSON_INVALID_UTF8_IGNORE , JSON_INVALID_UTF8_SUBSTITUTE , JSON_OBJECT_AS_ARRAY , JSON_THROW_ON_ERROR . The behaviour of these constants is described on the JSON constants page.

Return Values

Returns the value encoded in json in appropriate PHP type. Values true , false and null are returned as true , false and null respectively. null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting limit.

Errors/Exceptions

If depth is outside the allowed range, a ValueError is thrown as of PHP 8.0.0, while previously, an error of level E_WARNING was raised.

Changelog

Version Description
7.3.0 JSON_THROW_ON_ERROR flags was added.
7.2.0 associative is nullable now.
7.2.0 JSON_INVALID_UTF8_IGNORE , and JSON_INVALID_UTF8_SUBSTITUTE flags were added.
7.1.0 An empty JSON key («») can be encoded to the empty object property instead of using a key with value _empty_ .

Examples

Example #1 json_decode() examples

var_dump ( json_decode ( $json ));
var_dump ( json_decode ( $json , true ));

The above example will output:

object(stdClass)#1 (5) < ["a"] =>int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) > array(5) < ["a"] =>int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) >

Example #2 Accessing invalid object properties

Accessing elements within an object that contain characters not permitted under PHP’s naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

$obj = json_decode ( $json );
print $obj ->< 'foo-bar' >; // 12345

Example #3 common mistakes using json_decode()

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = «< 'bar': 'baz' >» ;
json_decode ( $bad_json ); // null

// the name must be enclosed in double quotes
$bad_json = ‘< bar: "baz" >‘ ;
json_decode ( $bad_json ); // null

// trailing commas are not allowed
$bad_json = ‘< bar: "baz", >‘ ;
json_decode ( $bad_json ); // null

Example #4 depth errors

// Encode some data with a maximum depth of 4 (array -> array -> array -> string)
$json = json_encode (
array(
1 => array(
‘English’ => array(
‘One’ ,
‘January’
),
‘French’ => array(
‘Une’ ,
‘Janvier’
)
)
)
);

// Show the errors for different depths.
var_dump ( json_decode ( $json , true , 4 ));
echo ‘Last error: ‘ , json_last_error_msg (), PHP_EOL , PHP_EOL ;

var_dump ( json_decode ( $json , true , 3 ));
echo ‘Last error: ‘ , json_last_error_msg (), PHP_EOL , PHP_EOL ;
?>

The above example will output:

array(1) < [1]=>array(2) < ["English"]=>array(2) < [0]=>string(3) "One" [1]=> string(7) "January" > ["French"]=> array(2) < [0]=>string(3) "Une" [1]=> string(7) "Janvier" > > > Last error: No error NULL Last error: Maximum stack depth exceeded

Example #5 json_decode() of large integers

var_dump ( json_decode ( $json ));
var_dump ( json_decode ( $json , false , 512 , JSON_BIGINT_AS_STRING ));

The above example will output:

object(stdClass)#1 (1) < ["number"]=>float(1.2345678901235E+19) > object(stdClass)#1 (1) < ["number"]=>string(20) "12345678901234567890" >

Notes

Note:

The JSON spec is not JavaScript, but a subset of JavaScript.

Note:

In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.

See Also

User Contributed Notes 8 notes

JSON can be decoded to PHP arrays by using the $associative = true option. Be wary that associative arrays in PHP can be a «list» or «object» when converted to/from JSON, depending on the keys (of absence of them).

You would expect that recoding and re-encoding will always yield the same JSON string, but take this example:

$json = »;
$array = json_decode($json, true); // decode as associative hash
print json_encode($array) . PHP_EOL;

This will output a different JSON string than the original:

The object has turned into an array!

Similarly, a array that doesn’t have consecutive zero based numerical indexes, will be encoded to a JSON object instead of a list.

$array = [
‘first’,
‘second’,
‘third’,
];
print json_encode($array) . PHP_EOL;
// remove the second element
unset($array[1]);
print json_encode($array) . PHP_EOL;

The array has turned into an object!

In other words, decoding/encoding to/from PHP arrays is not always symmetrical, or might not always return what you expect!

On the other hand, decoding/encoding from/to stdClass objects (the default) is always symmetrical.

Arrays may be somewhat easier to work with/transform than objects. But especially if you need to decode, and re-encode json, it might be prudent to decode to objects and not arrays.

If you want to enforce an array to encode to a JSON list (all array keys will be discarded), use:

If you want to enforce an array to encode to a JSON object, use:

Источник

json_decode возвращает JSON_ERROR_SYNTAX, но он-лайн форматировщик говорит, что JSON в порядке

Я столкнулся с той же проблемой, на самом деле есть некоторые скрытые символы, невидимые, и вам нужно удалить его.
Вот глобальный код, который работает во многих случаях:

 $checkLogin = str_replace(chr(127), "", $checkLogin); // This is the most common part // Some file begins with 'efbbbf' to mark the beginning of the file. (binary level) // here we detect it and we remove it, basically it's the first 3 characters if (0 === strpos(bin2hex($checkLogin), 'efbbbf')) < $checkLogin = substr($checkLogin, 3); >$checkLogin = json_decode( $checkLogin ); print_r($checkLogin); ?> 

Другие решения

Удаление BOM (Byte Order Mark) часто является решением, которое вам нужно:

function removeBOM($data) < if (0 === strpos(bin2hex($data), 'efbbbf')) < return substr($data, 3); >return $data; > 

У вас не должно быть спецификации, но если она есть, она невидима, поэтому вы ее не увидите !!

использование BOM Cleaner если у вас есть много файлов, чтобы исправить.

Я решил эту проблему, добавив stripslashes в строку, перед json_decode.

$data = stripslashes($data); $obj = json_decode($data); 

Чтобы собрать все вместе, я подготовил JSON-оболочку с расшифровкой автокорректирующих действий. Самую последнюю версию можно найти в моем GitHub Gist .

abstract class Json < public static function getLastError($asString = FALSE) < $lastError = \json_last_error(); if (!$asString) return $lastError; // Define the errors. $constants = \get_defined_constants(TRUE); $errorStrings = array(); foreach ($constants["json"] as $name =>$value) if (!strncmp($name, "JSON_ERROR_", 11)) $errorStrings[$value] = $name; return isset($errorStrings[$lastError]) ? $errorStrings[$lastError] : FALSE; > public static function getLastErrorMessage() < return \json_last_error_msg(); >public static function clean($jsonString) < if (!is_string($jsonString) || !$jsonString) return ''; // Remove unsupported characters // Check http://www.php.net/chr for details for ($i = 0; $i public static function encode($value, $options = 0, $depth = 512) < return \json_encode($value, $options, $depth); >public static function decode($jsonString, $asArray = TRUE, $depth = 512, $options = JSON_BIGINT_AS_STRING) < if (!is_string($jsonString) || !$jsonString) return NULL; $result = \json_decode($jsonString, $asArray, $depth, $options); if ($result === NULL) switch (self::getLastError()) < case JSON_ERROR_SYNTAX : // Try to clean json string if syntax error occured $jsonString = self::clean($jsonString); $result = \json_decode($jsonString, $asArray, $depth, $options); break; default: // Unsupported error >return $result; > > 
$json_data = file_get_contents("test.json"); $array = Json::decode($json_data, TRUE); var_dump($array); echo "Last error (" , Json::getLastError() , "): ", Json::getLastError(TRUE), PHP_EOL; 

Вы не показывали свой JSON, но это похоже на то, что это может быть неверная последовательность UTF-8 в аргументе, большинство онлайн-валидаторов не поймают его.
убедитесь, что ваши данные UTF-8, а также проверьте, есть ли у вас иностранные символы.
Вам не нужен PHP5, чтобы увидеть вашу ошибку, используйте журнал ошибок() регистрировать проблемы.

Попробовав все решение без результата, это сработало для меня.

Надеюсь, это поможет кому-то

У меня была такая же проблема. Для меня это было вызвано echo «
» , Я пытался передать строку JSON в другой файл PHP с помощью exit(json_encode(utf8ize($resp_array))); В начале файла я объявил линия разрыва тег … Так что это была ошибка для меня. Удаление этого разрыв строки тега , Я был в состоянии расшифровать мою строку JSON другой файл PHP ..

У меня была такая же проблема. Для меня это было вызвано echo «
» ,

Я пытался передать строку JSON в другой файл PHP с помощью:

exit(json_encode(utf8ize($resp_array))); 

В начале файла я объявил тег разрыва строки … Так что это была ошибка для меня. Удалив этот тег разрыва строки, я смог […]

Источник

json_decode возвращает JSON_ERROR_SYNTAX, но он-лайн форматировщик говорит, что JSON в порядке

У меня возникла очень странная проблема. У меня есть веб-сервис JSON. Когда я проверю его с помощью этого веб-сайта http://www.freeformatter.com/json-formatter.html#ad-output Все в порядке. Но когда я загружаю свой JSON с помощью этого кода:

 $data = file_get_contents('http://www.mywebservice'); if(!empty($data))

Я получил ошибку: SYNTAX ERROR КОТОРЫЙ НЕ ПОМОГАЕТ ПОЛНОМ ВСЕМ. Это кошмар. Я вижу, что с помощью PHP 5.5 я мог бы использовать эту функцию: http://php.net/manual/en/function.json-last-error-msg.php (но мне еще не удалось установить PHP 5.5, и я не уверен, что эта функция даст мне больше деталей)

Может быть, вы должны сделать ваши сообщения об ошибках более подробными? Например, включить JSON с сообщением об ошибке?

7 ответов

Я столкнулся с той же проблемой, на самом деле есть невидимые скрытые символы, и вам нужно удалить их. Вот глобальный код, который работает во многих случаях:

 $checkLogin = str_replace(chr(127), "", $checkLogin); // This is the most common part // Some file begins with 'efbbbf' to mark the beginning of the file. (binary level) // here we detect it and we remove it, basically it the first 3 characters if (0 === strpos(bin2hex($checkLogin), 'efbbbf')) < $checkLogin = substr($checkLogin, 3); >$checkLogin = json_decode( $checkLogin ); print_r($checkLogin); ?> 

Уважаемый сэр, вы понятия не имеете, насколько это помогло мне. Я везде искал решение и почти сдался. Сэр, вы находка.

+1 за спецификацию, не пришло в голову. @GeorgeOnofrei GeorgeOnofrei, принцип единой ответственности будет диктовать, что целью этой функции не является выполнение санации, если строка содержит недопустимые символы или спецификацию, которая технически не является частью самого документа JSON!

Удаление спецификации (отметка байтового байта) часто — это необходимое вам решение:

function removeBOM($data) < if (0 === strpos(bin2hex($data), 'efbbbf')) < return substr($data, 3); >return $data; > 

У вас нет спецификации, но если она там, она невидима, поэтому вы ее не увидите!!

используйте BOM Cleaner, если у вас есть много файлов для исправления.

Я изменил кодировку с UTF-8 UTF-8 without BOM Notepad++ из top menu of Notepad++>Format>UTF-8 without BOM

Я решил эту проблему добавить stripslashes в строку, перед json_decode.

$data = stripslashes($data); $obj = json_decode($data); 

Чтобы собрать все вещи здесь и там, я подготовил JSON-обертку с автоматическими корректирующими действиями декодирования.

abstract class Json < public static function getLastError($asString = FALSE) < $lastError = \json_last_error(); if (!$asString) return $lastError; // Define the errors. $constants = \get_defined_constants(TRUE); $errorStrings = array(); foreach ($constants["json"] as $name =>$value) if (!strncmp($name, "JSON_ERROR_", 11)) $errorStrings[$value] = $name; return isset($errorStrings[$lastError]) ? $errorStrings[$lastError] : FALSE; > public static function getLastErrorMessage() < return \json_last_error_msg(); >public static function clean($jsonString) < if (!is_string($jsonString) || !$jsonString) return ''; // Remove unsupported characters // Check http://www.php.net/chr for details for ($i = 0; $i public static function encode($value, $options = 0, $depth = 512) < return \json_encode($value, $options, $depth); >public static function decode($jsonString, $asArray = TRUE, $depth = 512, $options = JSON_BIGINT_AS_STRING) < if (!is_string($jsonString) || !$jsonString) return NULL; $result = \json_decode($jsonString, $asArray, $depth, $options); if ($result === NULL) switch (self::getLastError()) < case JSON_ERROR_SYNTAX : // Try to clean json string if syntax error occured $jsonString = self::clean($jsonString); $result = \json_decode($jsonString, $asArray, $depth, $options); break; default: // Unsupported error >return $result; > > 
$json_data = file_get_contents("test.json"); $array = Json::decode($json_data, TRUE); var_dump($array); echo "Last error (" , Json::getLastError() , "): ", Json::getLastError(TRUE), PHP_EOL; 

Я целый день боролся со странно закодированным файлом, содержащим JSON, и этот класс наконец-то дал мне полезный массив PHP — спасибо!

Источник

Читайте также:  Minecraft python api как установить
Оцените статью