(PHP 5 >= 5.3.0, PHP 7, PHP 8)
json_last_error — Devuelve el último error JSON
Devuelve el último error, si ha ocurrido, durante la última
operación de validación/codificación/decodificación JSON, que no haya especificado
JSON_THROW_ON_ERROR .
Esta función no contiene ningún parámetro.
Devuelve una de las siguientes constantes:
| Constante | Significado | Disponibilidad |
|---|---|---|
JSON_ERROR_NONE |
No ha ocurrido ningún error | |
JSON_ERROR_DEPTH |
Se ha alcanzado la profundidad máxima de la pila | |
JSON_ERROR_STATE_MISMATCH |
JSON inválido o mal formado | |
JSON_ERROR_CTRL_CHAR |
Error durante el control de caracteres; probablemente un codificación incorrecta | |
JSON_ERROR_SYNTAX |
Error de sintaxis | |
JSON_ERROR_UTF8 |
Caracteres UTF-8 malformados, posiblemente mal codificados | |
JSON_ERROR_RECURSION |
Una o más referencias recursivas están presentes en el valor a codificar | |
JSON_ERROR_INF_OR_NAN |
Una o más valores
NAN
o INF
están presentes en el valor a codificar.
|
|
JSON_ERROR_UNSUPPORTED_TYPE |
Se ha proporcionado un valor de un tipo que no puede ser codificado | |
JSON_ERROR_INVALID_PROPERTY_NAME |
Se ha proporcionado un nombre de propiedad que no puede ser codificado | |
JSON_ERROR_UTF16 |
Caracteres UTF-16 mal formados, probablemente mal codificados | |
JSON_ERROR_NON_BACKED_ENUM |
El valor contiene un enum sin valores (non-backed enum) que no se puede serializar. Disponible a partir de PHP 8.1.0. |
Ejemplo #1 Ejemplo con json_last_error()
<?php
// Una cadena JSON válida
$json[] = '{"Organisation": "Équipe de Documentation PHP"}';
// Una cadena json inválida que va a generar un error de sintaxis,
// aquí, uso de ' en lugar de "
$json[] = "{'Organisation': 'Équipe de Documentation PHP'}";
foreach ($json as $string) {
echo 'Decodificación: ' . $string;
json_decode($string);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - Sin errores';
break;
case JSON_ERROR_DEPTH:
echo ' - Profundidad máxima alcanzada';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Inadecuación de modos o underflow';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Error durante el control de caracteres';
break;
case JSON_ERROR_SYNTAX:
echo ' - Error de sintaxis; JSON malformado';
break;
case JSON_ERROR_UTF8:
echo ' - Caracteres UTF-8 malformados, probablemente un error de codificación';
break;
default:
echo ' - Error desconocido';
break;
}
echo PHP_EOL;
}
?>El ejemplo anterior mostrará:
Decodificación: {"Organisation": "Équipe de Documentation PHP"} - Sin errores
Decodificación: {'Organisation': 'Équipe de Documentation PHP'} - Error de sintaxis; JSON malformado
Ejemplo #2 json_last_error() con json_encode()
<?php
// Una secuencia UTF8 inválida
$text = "\xB1\x31";
$json = json_encode($text);
$error = json_last_error();
var_dump($json, $error === JSON_ERROR_UTF8);
?>El ejemplo anterior mostrará:
string(4) "null" bool(true)
Ejemplo #3 json_last_error() y JSON_THROW_ON_ERROR
<?php
// Una secuencia UTF8 inválida que causa JSON_ERROR_UTF8
json_encode("\xB1\x31");
// Esto no produce un error JSON
json_encode('okay', JSON_THROW_ON_ERROR);
// El estado de error global no ha sido modificado por el json_encode() anterior
var_dump(json_last_error() === JSON_ERROR_UTF8);
?>El ejemplo anterior mostrará:
bool(true)
While this can obviously change between versions, the current error codes are as follows:
0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8
I'm only posting these for people who may be trying to understand why specific JSON files are not being decoded. Please do not hard-code these numbers into an error handler routine.I used this simple script, flicked from StackOverflow to escape from the function failing:
<?php
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
?>
Cheers,
Praveen Kumar!when json_decode a empty string, PHP7 will trigger an Syntax error:
<?php
json_decode("");
var_dump(json_last_error(), json_last_error_msg());
// PHP 7
int(4)
string(12) "Syntax error"
// PHP 5
int(0)
string(8) "No error"use this code with mb_convert_encoding, you can json_encode some corrupt UTF-8 chars
function safe_json_encode($value, $options = 0, $depth = 512) {
$encoded = json_encode($value, $options, $depth);
if ($encoded === false && $value && json_last_error() == JSON_ERROR_UTF8) {
$encoded = json_encode(utf8ize($value), $options, $depth);
}
return $encoded;
}
function utf8ize($mixed) {
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = utf8ize($value);
}
} elseif (is_string($mixed)) {
return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
}
return $mixed;
}Just adding this note since I had to code this for the actual values reference.
<?php
echo JSON_ERROR_NONE . ' JSON_ERROR_NONE' . '<br />';
echo JSON_ERROR_DEPTH . ' JSON_ERROR_DEPTH' . '<br />';
echo JSON_ERROR_STATE_MISMATCH . ' JSON_ERROR_STATE_MISMATCH' . '<br />';
echo JSON_ERROR_CTRL_CHAR . ' JSON_ERROR_CTRL_CHAR' . '<br />';
echo JSON_ERROR_SYNTAX . ' JSON_ERROR_SYNTAX' . '<br />';
echo JSON_ERROR_UTF8 . ' JSON_ERROR_UTF8' . '<br />';
echo JSON_ERROR_RECURSION . ' JSON_ERROR_RECURSION' . '<br />';
echo JSON_ERROR_INF_OR_NAN . ' JSON_ERROR_INF_OR_NAN' . '<br />';
echo JSON_ERROR_UNSUPPORTED_TYPE . ' JSON_ERROR_UNSUPPORTED_TYPE' . '<br />';
/*
The above outputs :
0 JSON_ERROR_NONE
1 JSON_ERROR_DEPTH
2 JSON_ERROR_STATE_MISMATCH
3 JSON_ERROR_CTRL_CHAR
4 JSON_ERROR_SYNTAX
5 JSON_ERROR_UTF8
6 JSON_ERROR_RECURSION
7 JSON_ERROR_INF_OR_NAN
8 JSON_ERROR_UNSUPPORTED_TYPE
*/
?>This is a quite simple and functional trick to validate JSON's strings.
<?php
function json_validate($string) {
if (is_string($string)) {
@json_decode($string);
return (json_last_error() === JSON_ERROR_NONE);
}
return false;
}
echo (json_validate('{"test": "valid JSON"}') ? "It's a JSON" : "NOT is a JSON"); // prints 'It's a JSON'
echo (json_validate('{test: valid JSON}') ? "It's a JSON" : "NOT is a JSON"); // prints 'NOT is a JSON' due to missing quotes
echo (json_validate(array()) ? "It's a JSON" : "NOT is a JSON"); // prints 'NOT is a JSON' due to a non-string argument
?>
CheersProtected and private properties are ignored,
when json_encoding a class instance.
The snippet
<?php
class Example
{
private $privateprop = "private property";
protected $protectedprop = "protected property";
public $publicprop = "public property";
}
echo json_encode(new Example);
?>
only returns
{"publicprop":"public property"}here is a small updated version of utf8ize that has the following addition :
* It uses iconv instead of utf8_encode for potentially better result.
* It adds the support of objects variable
* It also update array key value (in a case I met I had to utf8ize the key as well as those were generated from a user input value)
Here is the code.
<?php
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
unset($d[$k]);
$d[utf8ize($k)] = utf8ize($v);
}
} else if (is_object($d)) {
$objVars = get_object_vars($d);
foreach($objVars as $key => $value) {
$d->$key = utf8ize($value);
}
} else if (is_string ($d)) {
return iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($d));
}
return $d;
}
?>