tags:

views:

44

answers:

3

When passing HTML back through a response in JSON format, does it need to get encoded?

A: 

Check this out: http://forum.jquery.com/topic/passing-html-via-json

Tommy
+1  A: 

Simple answer "no" JSON does not need to be encoded when passed back in JSON. JSON object should be DIRECTLY parsable by a javascript engine. Check the following:

Elf King
+2  A: 

Yes. You would pass the HTML code in a string, so any quotation marks and backslashes in the code would have to be encoded.

Example:

<div onclick="alert('Line 1\nLine2');">show</div>

would be encoded into a string like this:

"<div onclick=\"alert('Line 1\\nLine2');\">show</div>"

and for example put in a JSON object representation like this:

{"html":"<div onclick=\"alert('Line 1\\nLine2');\">show</div>"}
Guffa
In addition, any control characters must be escaped. I'd only expect to find \r, \n, and \t, but that doesn't preclude others. Whatever JSON framework you're using should be able to do this properly for you.
Thanatos