In my web application, I am trying to build a JSON string on the server and then pass this to the client so I can process it with some client side javascript. This works most of the time, however when the JSON string contains a single quote, the javascript breaks.
The JSON is basically a list of maps, which is passed into my GSP page in the mappings
variable. I then evaluate the string to convert it into a javascript object:
var json = eval('(${mappings})');
When mappings
is evaluated, the complete javascript expression looks something like this:
var json = eval('([{"targetId":123,"targetName":"this isn't going to work"}])');
So clearly, in this case when mappings
contains a single quote ("...this isn't going to work..."), the JSON string is terminated prematurely and the browser reports a javascript error.
I would have expected this to be easy to work around, however on the java side, when I try to replace '
with \\'
using
json.replaceAll("'", "\\'")
I get this:
"...this isn't going to work..."
ie it doesn't change at all!
If I try to double escape the backslash, ie
json.replaceAll("'", "\\\\'")
I get this:
"...this isn\\'t going to work..."
Which isn't correct either. How can I replace the single quote with a single backslash and quote so that when the string is rendered on the client it can be evaluated properly?
Don't use eval
. If you're inserting a JSON string into JavaScript, just insert it.
var json = ${mappings};
No escaping needed, the string is already valid JavaScript. (And if you do ever need to parse JSON, please use JSON.parse()
and not eval()
. It slows down your code significantly.)
You don't need regex here. Just use String#replace
method to escape single quotes:
String repl = "this isn't going to work".replace("'", "\\'");
//=> this isn\'t going to work
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.