Edit report at https://bugs.php.net/bug.php?id=62422&edit=1
ID: 62422 Updated by: ahar...@php.net Reported by: arnfda at gmail dot com Summary: Function that always produces legal JSON Status: Open Type: Feature/Change Request Package: JSON related Operating System: OS X 10.6.8 PHP Version: 5.4.4 Block user comment: N Private report: N New Comment: My initial gut feeling is to Won't Fix this: automatically casting a scalar input to an array or object is decidedly weird. I guess we could generate a notice to note that scalar inputs result in non-RFC output. At any rate, Crockford himself is ambiguous on the validity of isolated JSON primitives. The RFC grammar doesn't permit them, but the text suggests that they may be permitted, the json.org grammar chart doesn't express an opinion, the reference encoder allows them and encodes and decodes the same way as PHP, and he told Joey in an e-mail (after we debated this on IRC a couple of years back and Joey e-mailed him) that the RFC was only written to associate the MIME type with the format and that "it is not the spec". (Joey can presumably furnish the entire details of the exchange; I'm quoting him quoting Crockford.) In summary, even a simple spec like JSON is a bit of a choose your own adventure. I wouldn't be completely against a notice, but I don't think we should change the behaviour, both for BC and interoperability reasons. Previous Comments: ------------------------------------------------------------------------ [2012-06-26 14:58:55] arnfda at gmail dot com Description: ------------ json_encode generates illegal JSON when it is passed a string, boolean, or number. This behavior is noted here, along with a workaround: http://www.php.net/manual/en/function.json-encode.php#92817 json_decode accepts the illegal JSON, but other parsers that are more strict do not (for example, MultiJson in Ruby). I know the documentation doesn't promise to return valid JSON text, just the "JSON representation" of whatever is passed into it. So strictly speaking, this isn't a bug. But it doesn't make sense to have a function that creates JSON fragments and not one that always produces legal JSON that you can safely pass to other systems. It would be great if an option was added to json_encode that forced it to produce legal JSON strings, e.g. by wrapping single values in brackets as in the examples below. Test script: --------------- var_dump(json_encode(1)); var_dump(json_encode(true)); var_dump(json_encode("string")); Expected result: ---------------- string(3) "[1]" string(6) "[true]" string(10) "["string"]" Actual result: -------------- string(1) "1" string(4) "true" string(8) ""string"" ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=62422&edit=1