note 126787 added to function.json-decode
| From: | LennartHengstmengel at main dot php dot net | Date: | Fri, 21 Jan 2022 17:42:33 +0000 |
| Subject: | note 126787 added to function.json-decode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-217528@lists.php.net to get a copy of this message | ||
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
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.135 (proxied: 80.56.250.62)
----
Manual Page -- https://php.net/manual/en/function.json-decode.php
Edit -- https://main.php.net/note/edit/126787
Del: integrated -- https://main.php.net/note/delete/126787/integrated
Del: useless -- https://main.php.net/note/delete/126787/useless
Del: bad code -- https://main.php.net/note/delete/126787/bad+code
Del: spam -- https://main.php.net/note/delete/126787/spam
Del: non-english -- https://main.php.net/note/delete/126787/non-english
Del: in docs -- https://main.php.net/note/delete/126787/in+docs
Del: other reasons-- https://main.php.net/note/delete/126787
Reject -- https://main.php.net/note/reject/126787
Search -- https://main.php.net/manage/user-notes.php