Req #81112 [Opn]: Special json_encode behavior for SplFixedArray
Edit report at https://bugs.php.net/bug.php?id=81112&edit=1
ID: 81112
Updated by: nikic@php.net
Reported by: parsonswy at gmail dot com
Summary: Special json_encode behavior for SplFixedArray
Status: Open
Type: Feature/Change Request
Package: SPL related
Operating System: Ubuntu 20.04.2
PHP Version: 8.0.7
Block user comment: N
Private report: N
New Comment:
Adding a JsonSerializable implementation to SplFixedArray would make sense to me.
Previous Comments:
------------------------------------------------------------------------
[2021-06-06 20:04:08] parsonswy at gmail dot com
Description:
------------
SplFixedArray is a class and it's objects are therefore serialized as objects ('{}')
by json_encode(), not arrays ('[]'). I've marked this as a feature change because I
believe this is technically what is supposed to happen since SplFixedArrays are objects, but I also
think this current behavior is not intuitive or useful. SplFixedArray only accepts numeric indices
and should always be representable as a JSON array. This would be consistent with the behavior of
the primitive array type which will serialize as an array so long as there are no non-integer keys.
My current use case is developing a RESTful API which is queried by Javascript clients. It is
annoying to either cast SplFixedArray objects to (array)s before serializing them, or convert them
client side. Index access is the same in Javascript whether the key is '0' or the Integer
0, but having a map instead of an array means functions like Array.map() do not work.
I couldn't find any discussion in an existing bug ticket where a decision about this special
case had been made. This ticket https://bugs.php.net/bug.php?id=76186 is similar,
but I think SplFixedArrays warrant a separate decision as ArrayObjects support Map-like access with
non-numeric keys and SplFixedArrays do not.
Test script:
---------------
$spl_array = new SplFixedArray(1);
$std_array = [];
echo json_encode($spl_array) . PHP_EOL;
echo json_encode( (array) $spl_array ) . PHP_EOL;
echo json_encode($std_array);
$std_array[] = ['0 value'];
echo json_encode($std_array) . PHP_EOL;
Expected result:
----------------
[null] // SplFixedArray intuitive behavior
[null] // Explicit array cast work around to achieve intuitive behavior
// normal array behavior, when representable as array
[]
["0_value"]
Actual result:
--------------
{"0":null} // SplFixedArray current behavior
[null] // Explicit array cast work around to achieve intuitive behavior
// normal array behavior, when representable as array
[]
["0_value"]
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=81112&edit=1
Thread (4 messages)