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.

3 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

Leave a comment

Comment in textile images by gravatar