Stan Vassilev | FM wrote:
>>> var foo = <?=json_encode($my_string)?>;
>>> ... (yes, they maybe heared somewhere that JSON is *not* javascript, I
>>> told 'em too).
> 
> JSON is a strict subset of JavaScript, and the above scenario is
> something I also do often.
> 
> Since PHP generates web pages, any time I need to generate a JS literal
> json_encode() is the natural equivalent of var_export(.., true) for PHP
> literals.
> 
> Since it may not match the RFC apparently, I suggest a flag as some
> other people said:
> 
> function json_encode($var, $allowScalar = false) {}

I'm not sure if that is the right way of looking at it though.  I think
the only question is how to represent the scalar types, not whether they
should be allowed.  As far as I am concerned it is obvious that they be
allowed and the JSON spec is quite explicit that JSON can be used to
represent scalar types:

   JSON can represent four primitive types (strings, numbers,
   booleans, and null) and two structured types (objects and arrays).

The only question is how to serialize these into a JSON-text string.
Again, from the RFC:

   A JSON text is a sequence of tokens.  The set of tokens includes six
   structural characters, strings, numbers, and three literal names.

   A JSON text is a serialized object or array.

This last statement is the issue.  When serializing a basic type into a
JSON text string, the RFC says we need to wrap it inside an array or
object.  So, if we are going to add an option to json_encode(), that's
what the option should do.  Specify whether, and perhaps how, to wrap
basic types, not whether to allow or disallow them.

I'll talk to Douglas on Monday if he is in the office and get his opinion.

-Rasmus

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to