json_decode

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0)

json_decodeDecodifica un string de JSON

Descripción

json_decode(
    string $json,
    bool $assoc = false,
    int $depth = 512,
    int $options = 0
): mixed

Convierte un string codificado en JSON a una variable de PHP.

Parámetros

json

El string de json a decodificar.

Esta función sólo trabaja con string codificados en UTF-8.

Nota:

PHP implementa un superconjunto de JSON tal como se especifica en la » RFC 7159 original.

assoc

Cuando es true, los object devueltos serán convertidos a array asociativos.

depth

Profundidad de recursividad especificada por el usuario.

options

Máscara de bit de opciones de decodificación de JSON. Actualmente solamente está soportada JSON_BIGINT_AS_STRING (por defecto, convierte enteros grandes en valores de tipo float)

Valores devueltos

Devuelve el valor codificado en json en un tipo de PHP apropiado. Los valores true, false y null son devueltos como true, false y null respectivamente. null es devuelto si el parámetro json no se puede decodificar o si los datos codificados son más profundos que el límite de recursividad.

Ejemplos

Ejemplo #1 Ejemplos de json_decode()

<?php
$json 
'{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($jsontrue));

?>

El resultado del ejemplo sería:

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)
}

Ejemplo #2 Acceder a propiedades de objeto no válidas

Se puede acceder a elementos de un objeto que contienen caracteres no permitidos por la convención de nombres de PHP (p.ej., el guión) encapsulando el nombre del elemento entre llaves y apóstrofe.

<?php

$json 
'{"foo-bar": 12345}';

$obj json_decode($json);
print 
$obj->{'foo-bar'}; // 12345

?>

Ejemplo #3 Errores comunes al usar json_decode()

<?php

// los siguientes string son válidos en JavaScript pero no en JSON

// el nombre y el valor deben estar entre comillas dobles
// las comillas simples no son válidas
$json_erróneo "{ 'bar': 'baz' }";
json_decode($json_erróneo); // null

// el nombre debe estar entre comillas dobles
$json_erróneo '{ bar: "baz" }';
json_decode($json_erróneo); // null

// las comas finales no están permitidas
$json_erróneo '{ bar: "baz", }';
json_decode($json_erróneo); // null

?>

Ejemplo #4 Errores con depth

<?php
// Codificar los datos.
$json json_encode(
    array(
        
=> array(
            
'Inglés' => array(
                
'One',
                
'January'
            
),
            
'Francés' => array(
            
'Une',
            
'Janvier'
            
)
        )
    )
);

// Definir los errores.
$constantes get_defined_constants(true);
$errores_json = array();
foreach (
$constantes["json"] as $nombre => $valor) {
    if (!
strncmp($nombre"JSON_ERROR_"11)) {
        
$errores_json[$valor] = $nombre;
    }
}

// Mostrar los errores para diferentes profundidades.
foreach (range(43, -1) as $profundidad) {
    
var_dump(json_decode($jsontrue$profundidad));
    echo 
'Último error: '$errores_json[json_last_error()], PHP_EOLPHP_EOL;
}
?>

El resultado del ejemplo sería:

array(1) {
  [1]=>
  array(2) {
    ["Inglés"]=>
    array(2) {
      [0]=>
      string(3) "One"
      [1]=>
      string(7) "January"
    }
    ["Francés"]=>
    array(2) {
      [0]=>
      string(3) "Une"
      [1]=>
      string(7) "Janvier"
    }
  }
}
Último error: JSON_ERROR_NONE

NULL
Último error: JSON_ERROR_DEPTH

Ejemplo #5 json_decode() de enteros grandes

<?php
$json 
'{"number": 12345678901234567890}';

var_dump(json_decode($json));
var_dump(json_decode($jsonfalse512JSON_BIGINT_AS_STRING));

?>

El resultado del ejemplo sería:

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

Notas

Nota:

La especificación de JSON no es JavaScript, pero sí un subconjunto de JavaScript.

Nota:

En el caso de ocurrir un error durante la decodificación, se puede usar json_last_error() para determinar la naturaleza exacta del mismo.

Historial de cambios

Versión Descripción
5.6.0 Ya no se aceptan variantes que no estén en minúsculas de los literales true, false y null como entradas válidas, por lo que se generarán advertencias.
5.4.0 Se añadió el parámetro options.
5.3.0 Se añadió el parámetro opcional depth. La profundidad de recursividad predeterminada se aumentó de 128 a 512
5.2.3 La profundidad de recursividad predeterminada se aumentó de 20 a 128
5.2.1 Se añadió soporte para la decodificación de JSON de tipos básicos.

Ver también

add a note add a note

User Contributed Notes 4 notes

up
1
Alien426
3 years ago
Browsers don't choke on integers _starting_ with BigInt (64 bits), but before that (53 bits). The introduction of BigInt to modern browsers doesn't help much, when JSON handling functions do not support it. So I am trying to remedy that. My approach is to handle the decoded array before re-encoding it to a string:
<?php
function fix_large_int(&$value)
{
  if (
is_int($value) && $value > 9007199254740991)
   
$value = strval($value);
}
$json_str = '{"id":[1234567890123456789,12345678901234567890]}';
$json_arr = json_decode($json_str, flags: JSON_BIGINT_AS_STRING | JSON_OBJECT_AS_ARRAY);
echo(
json_encode($json_arr)); // {"id":[1234567890123456789,"12345678901234567890"]} (BigInt is already converted to a string here)
array_walk_recursive($json_arr, 'fix_large_int');
echo(
json_encode($json_arr)); // {"id":["1234567890123456789","12345678901234567890"]}
?>
up
0
greaties at ghvernuft dot nl
3 years ago
To load an object with data in json format:

function loadJSON($Obj, $json)
{
    $dcod = json_decode($json);
    $prop = get_object_vars ( $dcod );
    foreach($prop as $key => $lock)
    {
        if(property_exists ( $Obj ,  $key ))
        {
            if(is_object($dcod->$key))
            {
                loadJSON($Obj->$key, json_encode($dcod->$key));
            }
            else
            {
                $Obj->$key = $dcod->$key;
            }
        }
    }
}
up
0
cubefox at web dot NOSPAMPLEASE dot de
3 years ago
Warning: As the section "return values" mentions, the return value NULL is ambiguos. To repeat, it can mean three things:

* The input string had the value "null"
* There was an error while parsing the input data
* The encoded data was deeper than the recursion limit

To distinguish these cases, json_last_error() can be used.
up
-7
mattia
3 years ago
if you're using ajax to post, and your JavaScript code looks like this:

<code>
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "something.php", true);
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
             // do something
        }
    };
    var data = {some: "thing"};
    xhttp.send(JSON.stringify(data));
</code>

then in <code>something.php</code> you can retrieve your json by doing

<?php
$data
= json_decode(file_get_contents("php://input"), true);
?>
To Top