Reputation: 32885
In CF (9.0.2 with esapi-2.0_rc10.jar
):
<cfset test = ['ha"ha"']>
<script>
x = JSON.parse('#encodeForJavaScript(serializeJSON(test))#');
y = JSON.parse('#replace(serializeJSON(test), '"', '\"', "all")#');
z = #serializeJSON(test)#;
j = JSON.parse('#jsStringFormat(serializeJSON(test))#');
</script>
Output:
<script>
x = JSON.parse('\x5B\x22ha\x22ha\x22\x22\x5D');
y = JSON.parse('[\"ha\\"ha\\"\"]');
z = ["ha\"ha\""];
j = JSON.parse('[\"ha\\\"ha\\\"\"]');
</script>
y
, z
and j
are valid.
x
actually fails: "Uncaught SyntaxError: Unexpected token h "
I thought encodeForJavaScript()
in ESAPI was supposed to be the best and safest function to be used in situation like this. Why does it fail here?
side question, if I'm only using serializeJSON()
, even if the data is dynamically built with user input, does it mean I don't really need to use JSON.parse
since there will be no functions in the JSON string for sure?
Upvotes: 0
Views: 1615
Reputation: 3884
If you use encodeForJavascript
on a JSON string, then it is no longer valid JSON.
Upvotes: 2
Reputation: 1350
Quote from JSON.org:
A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.
This is in the JSON context
This pic 'shows' the format for strings in json objects
Upvotes: 0