Search code examples
coldfusioncoldfusion-10esapi

encodeForJavaScript() with JSON.parse, doublequote woes


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?


Solution

  • If you use encodeForJavascript on a JSON string, then it is no longer valid JSON.