I have a Laravel app where this is in a Controller function:
$extraDataStr = (string) $request->input('extraData');
$extraData = json_decode($extraDataStr, true);
But even though $extraDataStr
is valid JSON (as shown in Xdebug), $extraData becomes an array that contains only keys that had non-null values in $extraDataStr
. This doesn't make any sense.
I thought I was losing my mind, so I even wrote a test of json_decode:
$extraDataStr = json_encode([
'willBeNull' => null,
'hasVal' => 4
]);
$extraDataArr = json_decode($extraDataStr, true);
$this->assertEquals(['willBeNull', 'hasVal'], array_keys($extraDataArr));
$this->assertNull($extraDataArr['willBeNull']);
It passes, of course.
So then I took that same line from the test and temporarily inserted it into the Controller function just to see whether somehow it would remove the nulls:
$extraDataStr = json_encode([
'willBeNull' => null,
'hasVal' => 4
]);
$extraData = json_decode($extraDataStr, true);
This erroneously omits keys with null values even when I'm using this basic json_encoded string rather than user input!
What the hell is going on?
P.S. This is not the same question as php json_decode removing attributes with null value because I've shown a test that passes and the exact code that is failing.