Many JSON serializer implementations escape the "/" character, including for
instance PHP's json_encode(). However, JavaScript's own JSON.stringify()
does not. If you look at the grammar on json.org, as I read it, the escaping
of "/" is **optional**, since it is a valid UNICODE character, and it's not
", \, or a control character.
I personally find this annoying as I never embed JSON into script tags like
that, and even if I do, my data never looks like </tag>. I wish that JSON
serializers, including JSON.stringify, had an option to control if you want
"/" to be escaped. It could of course default to whatever each
implementations current default behavior is, but I think it should be a
configurable behavior rather than baked in, one way or the other.
--Kyle
--------------------------------------------------
From: "Lasse Reichstein" <[email protected]>
Sent: Wednesday, April 13, 2011 4:26 AM
To: "EcmaScript Steen" <[email protected]>; "es5-discuss"
<[email protected]>; "Oliver Hunt" <[email protected]>
Subject: Re: Escaping of / in JSON
On Wed, 13 Apr 2011 07:30:58 +0200, Oliver Hunt <[email protected]> wrote:
It has recently been brought to my attention that a particular use case
of JSON serialisation is to include JSON serialised content directly
into an HTML file (inside a script tag). In this case in addition to
the threat of strings being terminated by a double quote there's also
the potential for the string "</script>" to terminate the JS source.
The request i received was to escape the slash character, which is
allowed as input but per ES5 spec we aren't allowed to emit.
I will say that I don't really like this idea as it leads to "why not
escape #?", etc but I thought I should bring this up on the list and see
what others think.
My personal opinion is that if you want to embed any string into any
formatted context, you need to be aware of the environment you are
plugging
things into.
If you put something into HTML, you need to know where in the HTML it is.
If it's an intrinsic event handler, the requirements are different than if
its
a script tag. In a script tag, it's not just "</" that's a problem, but
also, e.g.,
"<![CDATA[" and "<!--" if the HTML is actually XHTML or HTML5.
I don't want to start adding exceptions to JSON just to help one usecase.
I'd rather create a function for people to use that can convert a JSON
string
to valid HTML script element content (but not as part of the language,
it's too
HTML specific). It would fit better into HTML5, so that it can follow any
changes to the specification.
(On the other hand, RegExp.quotePattern and RegExp.quoteReplacement like
the Java
versions would make sense to have in ES).
/L
--
Lasse Reichstein - [email protected]
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss