note 86181 modified in function.json-decode by danbrown

From: Date: Sat, 02 May 2009 14:54:32 +0000
Subject: note 86181 modified in function.json-decode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154139@lists.php.net to get a copy of this message
json_decode()'s handling of invalid JSON is very flaky, and it is very hard to reliably determine if the decoding succeeded or not. Observe the following examples, none of which contain valid JSON: The following each returns NULL, as you might expect: <?php var_dump(json_decode('[')); // unmatched bracket var_dump(json_decode('{')); // unmatched brace var_dump(json_decode('{}}')); // unmatched brace var_dump(json_decode('{error error}')); // invalid object key/value notation var_dump(json_decode('["\"]')); // unclosed string var_dump(json_decode('[" \x "]')); // invalid escape code Yet the following each returns the literal string you passed to it: var_dump(json_decode(' [')); // unmatched bracket var_dump(json_decode(' {')); // unmatched brace var_dump(json_decode(' {}}')); // unmatched brace var_dump(json_decode(' {error error}')); // invalid object key/value notation var_dump(json_decode('"\"')); // unclosed string var_dump(json_decode('" \x "')); // invalid escape code ?> (this is on PHP 5.2.6) Reported as a bug, but oddly enough, it was closed as not a bug. [NOTE BY danbrown AT php DOT net: This was later re-evaluated and it was determined that an issue did in fact exist, and was patched by members of the Development Team. See http://bugs.php.net/bug.php?id=45989 for details.] --was-- json_decode()'s handling of invalid JSON is very flaky, and it is very hard to reliably determine if the decoding succeeded or not. Observe the following examples, none of which contain valid JSON: The following each returns NULL, as you might expect: var_dump(json_decode('[')); // unmatched bracket var_dump(json_decode('{')); // unmatched brace var_dump(json_decode('{}}')); // unmatched brace var_dump(json_decode('{error error}')); // invalid object key/value notation var_dump(json_decode('["\"]')); // unclosed string var_dump(json_decode('[" \x "]')); // invalid escape code Yet the following each returns the literal string you passed to it: var_dump(json_decode(' [')); // unmatched bracket var_dump(json_decode(' {')); // unmatched brace var_dump(json_decode(' {}}')); // unmatched brace var_dump(json_decode(' {error error}')); // invalid object key/value notation var_dump(json_decode('"\"')); // unclosed string var_dump(json_decode('" \x "')); // invalid escape code (this is on PHP 5.2.6) Reported as a bug, but oddly enough, it was closed as not a bug: http://bugs.php.net/bug.php?id=45989 http://php.net/manual/en/function.json-decode.php

« previous php.notes (#154139) next »