CakeFest 2024: The Official CakePHP Conference

json_decode

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

json_decodeDécode une chaîne JSON

Description

json_decode(
    string $json,
    ?bool $associative = null,
    int $depth = 512,
    int $flags = 0
): mixed

Récupère une chaîne encodée JSON et la convertit en une valeur de PHP.

Liste de paramètres

json

La chaîne de caractères json à décoder.

Cette fonction ne fonctionne qu'avec des chaînes encodées en UTF-8.

Note:

PHP implémente un sur-ensemble de JSON tel que spécifié dans la » RFC 7159 originale.

associative

Lorsque ce paramètre vaut true, les objets JSON seront retournés comme tableaux associatifs ; lorsque ce paramètre vaut false, les objets JSON seront retournés comme des objets. Lorsque ce paramètre vaut null, les objets JSON seront retournés comme des tableaux associatifs ou des objets, suivant si la constante JSON_OBJECT_AS_ARRAY a été définie dans le paramètre flags.

depth

Profondeur d'imbrication maximale de la structure en cours de décodage. La valeur doit être supérieure à 0, et inférieure ou égale à 2147483647.

flags

Masque de bit compris de JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR. Le comportement de ces constantes est décrite sur la page des constantes JSON.

Valeurs de retour

Retourne la valeur encodée dans le paramètre json dans le type PHP approprié. Les valeurs sans guillemets true, false et null sont retournées respectivement comme true, false et null. null est retourné si le paramètre json n'a pu être décodé ou si les données encodées sont plus profondes que la limite d'imbrication fournie.

Erreurs / Exceptions

Si depth est en dehors de la plage autorisée, une ValueError est lancée à partir de PHP 8.0.0, alors qu'auparavant, une erreur de niveau E_WARNING était levée.

Historique

Version Description
7.3.0 Le flags JSON_THROW_ON_ERROR a été ajouté.
7.2.0 Le paramètre associative est désormais nullable.
7.2.0 Les flags JSON_INVALID_UTF8_IGNORE, et JSON_INVALID_UTF8_SUBSTITUTE ont été ajouté.
7.1.0 Une clé JSON vide ("") peut être encodée dans la propriété d'objet vide au lieu d'utiliser une clé avec la valeur _empty_.

Exemples

Exemple #1 Exemple avec json_decode()

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

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

?>

L'exemple ci-dessus va afficher :

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

Exemple #2 Accès à des propriétés d'objet invalides

Accéder à des éléments d'un objet qui contiennent des caractères non permis par la convention de nommage de PHP (i.e. le trait d'union) peut être effectué en encapsulant le nom de l'élément avec des crochets et des apostrophes.

<?php

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

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

?>

Exemple #3 Erreurs habituelles lors de l'utilisation de la fonction json_decode()

<?php

// Les chaînes suivantes sont valides en JavaScript mais pas en JSON

// Le nom et la valeur doivent être entourés de guillemets doubles.
// Les guillemets simples ne sont pas valides.
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// Le nom doit être entouré de guillemets doubles.
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null

// La virgule de fin n'est pas autorisée.
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null

?>

Exemple #4 Erreurs avec le paramètre depth

<?php
// Encodage des données avec un niveau d'imbrication maximal de 4 (array -> array -> array -> string)
$json = json_encode(
array(
1 => array(
'English' => array(
'One',
'January'
),
'French' => array(
'Une',
'Janvier'
)
)
)
);

// Définition des erreurs
$constants = get_defined_constants(true);
$json_errors = array();
foreach (
$constants["json"] as $name => $value) {
if (!
strncmp($name, "JSON_ERROR_", 11)) {
$json_errors[$value] = $name;
}
}


$json = json_encode(
array(
1 => array(
'English' => array(
'One',
'January'
),
'French' => array(
'Une',
'Janvier'
)
)
)
);

// Affichage des erreurs pour des niveau d'imbrication différentes.
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;
?>

L'exemple ci-dessus va afficher :

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

Exemple #5 Exemple avec json_decode() et de gros entiers

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

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

?>

L'exemple ci-dessus va afficher :

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

Notes

Note:

La spécification JSON ne fait pas partie de Javascript mais d'un sous-projet de Javascript.

Note:

Si une erreur survient lors du décodage, la fonction json_last_error() (ou json_last_error_msg() avec PHP5.5+) pourra être utilisée pour déterminer la nature exacte de l'erreur.

Voir aussi

add a note

User Contributed Notes 8 notes

up
21
Lennart Hengstmengel
2 years ago
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 = '{"0": "No", "1": "Yes"}';
$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:

["No","Yes"]

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 output will be:

["first","second","third"]
{"0":"first","2":"third"}

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:

json_encode(array_values($array));

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

json_encode((object)$array);

See also: https://www.php.net/manual/en/function.array-is-list.php
up
4
greaties at ghvernuft dot nl
1 year ago
To load an object with data in json format:
(bugfixed my previous comment)

<?php
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;
}
}
}
return
$Obj;
}
?>

Tested with:

<?php
class Name
{
public
$first;
public
$last;
public function
fullname()
{
return
$this->first . " " . $this->last;
}
}
$json = '{"first":"John","last":"Smith"}';

$infull = loadJSON((new Name), $json);
echo
$infull->fullname();
up
3
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
2
Alien426
2 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
-4
greaties at ghvernuft dot nl
2 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
-6
as-works at narod dot ru
2 years ago
On some PHP7+ systems php_json functions can be undefined (i faced it on Oracle Linux Enterprice with php 7.4 installed from REMI repository). If you have the same problem, try to install separated php-json module:

# yum install php-json

Hope this helps.
up
-18
Anonymous
2 years ago
<?php

$array
= [0 => "foo", 1 => "bar", 2 => ["baz"]];

$associative = false;

var_dump(
json_decode(
json_encode($array),
$associative
)
);

?>

The above will output
<?php
/*
array (size=3)
0 => string 'foo' (length=3)
1 => string 'bar' (length=3)
2 =>
array (size=1)
0 => string 'baz' (length=3)
*/
?>

Considering <?php $associative = false; ?> one might expect
<?php
/*
object(stdClass)
public '0' => string 'foo' (length=3)
public '1' => string 'bar' (length=3)
public '2' =>
object(stdClass)
public '0' => string 'baz' (length=3)
*/
?>

an stdClass object instead of an array, but this is incorrect.
json_decode will always return an array for a sequentially encoded array, regardless of the ?bool $associative 2nd argument

Which is inline with the above mentioned docs/spec
> Returns the value encoded in json in appropriate PHP type

Considering that the 1st arg was a sequentially encoded array as a json string
'["foo","bar",["baz"]]'
up
-36
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