I am able to JSON encode and decode indexed arrays in a way that the decoded value matches the original input:
$array_indexed = ['A'];
$encoded = json_encode($array_indexed);
$decoded = json_decode($encoded);
var_dump($array_indexed);
array(1) {
[0]=>
string(1) "A"
}
var_dump($decoded);
array(1) {
[0]=>
string(1) "A"
}
However when I encode an associate array, I end up with an object:
$array_associate = [ 'FOO' => 'BAR'];
$encoded = json_encode($array_associate);
$decoded = json_decode($encoded);
var_dump($array_associate);
array(1) {
["FOO"]=>
string(3) "BAR"
}
var_dump($decoded);
object(stdClass)#1 (1) {
["FOO"]=>
string(3) "BAR"
}
My understanding is that this is normal behaviour since Javascript doesn't support associate arrays, which are represented instead using objects, hence when encoding an associating array, it ends up encoded as an object (and therefore decoded as such).
Q1: Do you confirm?
Possible solutions
serialize /unserialize:
The reason for absolutely wanting to use json_encode/json_decode over serialize /unserialize is that the encoded form is much more concise, which is important because it ends up stored in cache and cache space is limited:
var_dump(json_encode(['A'=>1,'B'=>2])); // string(13) "{"A":1,"B":2}"
var_dump(serialize(['A'=>1,'B'=>2])); // string(30) "a:2:{s:1:"A";i:1;s:1:"B";i:2;}
Q2: Have you ever been confronted with cache space issues using serialize, and if so how did you address is other than by using json_encode(I'm thinking compression, but if value is to end up in a MySQL DB cache I'm a bit uneasy with it)?
json_decode($json,true):
The problem is that nested objects that should remain objects are also converted to arrays:
$obj = new stdClass;
$obj->foo = 'bar';
$array_associate = [ 'A' => $obj];
$encoded = json_encode($array_associate);
var_dump(json_decode($encoded,true));
array(1) {
["A"]=>
array(1) { <---------------- NO LONGER AN OBJECT, DON'T WANT THAT
["foo"]=>
string(3) "bar"
}
}
convert object of objects to array of objects:
Still based on the above example
$object_of_objects = json_decode($encoded);
$array = [];
foreach($object_of_objects as $key=>$object) {
$array[$key] = $object;
}
var_dump($array);
array(1) {
["A"]=>
object(stdClass)#6 (1) {
["foo"]=>
string(3) "bar"
}
}
Q3: Do you see any other solution to convert associate array of objects to JSON and back while preserving original input?