When does php json_decode return false?

The PHP documentation for json_decode says that it can return TRUE , FALSE , NULL .

Can someone help me figure out when it will return FALSE ? I understand that invalid JSON will return NULL , but when will the other two be returned if not for the actual JSON value?

thanks

+7
json php
source share
2 answers

The JSON format definition clearly shows all possible values โ€‹โ€‹and their representations:

The value can be a double-quoted string or a number, either true or false or null , or an object or array.

Both objects and arrays have special syntax in the JSON representation (wrapped in {} and [] respectively), so they cannot be mixed with false in any case. The same thing happens with the string - it is wrapped in "" (double quotes). As for numbers, they must contain at least one digit, so it should not be confused with false (both true and null ).

So this leaves us with the only case: when json_encode processes an object, overriding its JSON representation. For example (PHP 5.4 +):

 class FalsyFoo implements JsonSerializable { public $foo; public function __construct($f) { $this->foo = $f; } public function jsonSerialize() { return false; } } $f = new FalsyFoo(true); $fj = json_encode($f); var_dump( $fj ); // string(5) 'false' var_dump( json_decode($fj) ); // bool(false) 

Technically, we are still working with false here, but the source is clearly different.


If you're still not sure, check out the json_decode source code , which php_json_decode_ex calls after checking the arguments. This, in turn, calls parse_JSON_ex , which works on a predefined state transition table ; the latter has only one set of states leading to false as a result. If this call fails, the value will be checked:

 if (str_len == 4) { if (!strcasecmp(str, "null")) { /* We need to explicitly clear the error because its an actual NULL and not an error */ jp->error_code = PHP_JSON_ERROR_NONE; RETVAL_NULL(); } else if (!strcasecmp(str, "true")) { RETVAL_BOOL(1); } } else if (str_len == 5 && !strcasecmp(str, "false")) { RETVAL_BOOL(0); } 

... and that the only case where return_value is boolean.

+6
source share

The documentation states that values true, false and null (case-insensitive) are returned as TRUE, FALSE and NULL respectively. This means that if the object to be encoded must have boolean true or false , they will be displayed as true or false , and the same for null. For example:

 json_decode('["hello",true]'); 

will return:

 ["hello",TRUE] 

This does not mean json_decode will return true , false or null

0
source share

All Articles