Check out my NEW training website for front-end web developers, FrontendMasters.com

Groovy JSON String Escape Quote

July 28, 2010

The project I’m working on at the moment is in Groovy. In order to set JSON on page load, you have to escape either single quotes or double quotes.

var myJSON = this is the cat\’s first day in Marc\‘s house; // JavaScript string

With groovy, you can cast something as JSON and set it to the view pretty easily.

// setting JSON object to view in grails
def myObject = [
id: id,
foo: foo
]
[myObject: myObject as JSON]

In the view, you can use jQuery’s parseJSON method to set the myJSON object from your server-side method.

// turning Groovy JSON object into JavaScript JSON in view
var myJSON = $.parseJSON(${myObject});

The problem comes when you have single quotes inside that JSON string.

“Strings are CON-FUSE-ING in groovy- I just want to print a dang backslash-quote “\’” nope try again.. ‘\\’" ..nope “\\\’” ..nope.. ‘\\\\’’ ..?" – 2AM Tweet frustration

I looked up countless articles, and found out that it is not actually strings that are a deal. With Groovy, you have to use four slashes s.replaceAll("'", "\\\\'"). See, Slashy Strings in Groovy. This is also outlined in a forum thread where people were complaining about Java itself, String.replaceAll troubles with regEx.

This is great if you want to print out a normal string:

// string replace single quote with backslash-quote in groovy
def myString = " the dog’s tail is being chased more’ quotes’ 09’ 10’ "
myString = myString.replaceAll("", "\\\\")

But won’t work is if you try to cast that object as JSON. I tried to do this inside an object and cast it as JSON then the once I set it to the view, \’ doesn’t print out.

If you have a solution for this great, but I solved my problem by getting the JSON via a simple AJAX $.get request.

Like this article? You'll like my NEW training website for front-end web developers!

Video workshops on jQuery, JavaScript, HTML5, web performance and more.
Upgrade your front-end developer skills!

5 comments

#1. Matt on July 28, 2010
s = s.replaceAll("", "\\\\u0027")
#2. Marc Grabanski on July 29, 2010

thanks Matt!

#3. Joseph Gutierrez on August 09, 2010

You might want to check this out:
http://stackoverflow.com/questions/2275359/jquery-single-quote-in-json-response

#4. Ankit Mathur on June 14, 2012

var encodedJSONOrg = encodeURIComponent(JSON.stringify(Object));

1:-Object any object that contains single qoutes.
2:-if any object have single quotes then you can use this line to remove single quotes by using replace method.
3:-run this line perfectly..
var encodedJSON2 = encodedJSONOrg.replace(/‘/g, "\\’\\’");
its working fine.

#5. Gabe Hamilton on November 20, 2012

“some string”.encodeAsJavaScript() worked for me.

Leave a comment

Comment in textile images by gravatar