views:

135

answers:

2

Hi all,

I have an AJAX request that creates a 'post', and upon successful post, I want to get HTML to inject back into the DOM. Right now I'm returning a JSON array that details success/error, and when I have a success I also include the HTML for the post in the response. So, I parse the response as JSON, and set a key in the JSON array to a bunch of HTML Code.

Naturally, the HTML code is making the JSON array break -- what should I do to escape it (or is there a better way to do this?). I get an AJAX response with a JSON array like so:

[{response:"success"},{html:'<div class="this is going to break...

Thanks!

+1  A: 

Contrary to what you're probably used to in JavaScript, ' can't begin a string in JSON. It's strictly a ". Single quotes work when you're passing JSON to JavaScript.. much like <br> works when you want to put an XHTML line break.

So, use " to open the HTML string, and sanitize your quotes with \".

json.org has more info WRT what you should sanitize. Though the list of special characters isn't long, it's probably best to use a library like Anurag suggests in a comment.

BranTheMan
oh, didn't know that :)
Ciwee
I should probably clarify: single quotes *work* when you're passing JSON to JavaScript.. much like <br> *works* when you want to put an XHTML line break.
BranTheMan
@Bran: you should have edited your question instead of commenting it.
Ciwee
Good idea. Done
BranTheMan
Cool, thanks for the info!
Jasie
+1  A: 

Apart from escaping double quotes as mention by BranTheMan, newlines also break JSON strings. You need to replace newlines with \n.

Personally I've found this to be enough:

// Don't know what your serverside language is, example in javascript syntax:

print(encodeJSON({
    response : "success",
    html : htmlString.replace(/\n/g,'\\n').replace(/"/g,'\\"')
}));
slebetman
Thank you! That will work.
Jasie