views:

55

answers:

1

Hi,

I'm trying to parse a JSON using Grails, to test the parser I Wrote an unit test and put my input JSON in a GString that looks something like this:

"""{"Information":"Some data here \"stuff\" some more.","AnswerToEverything":42,"Other":71,"Name":"Joe Doe"}"""

The \"stuff\" is causing the parser to break.

I tried using String.replace(/\\"/, "") and a few other combinations to remove the \" but it either does nothing or removes all the quotes from the string. This post tells me that I need to use 5 slashes: \\\\\" to get it to work in Java but it isn't working in Groovy.

Edit: This test should pass for it to work:

str = """foo \"foobar\" bar"""
assert  str.replace("""\\\"""", "")  == "foo foobar bar"

With the above regex it fails.

Any tips?

A: 

From what I can tell, regexps written with as /regexp/ seem to have trouble with escaped backslashes. You can write the regexp with the """ construct like so:

str = "\\\""
assert str[0] == "\\"
assert str[1] == "\""

assert str =~ """\\\""""
assert str.replace("""\\\"""", "") == ""

EDIT: The JSON in the original post doesn't contain any literal backslashes. You still need to escape literal backslashes even in """strings""". I'm guessing you want to escape those, like in json2 below:

json1 = """{"Information":"Some data here \"stuff\" some more.","AnswerToEverything":42,"Other":71,"Name":"Joe Doe"}"""
json2 = """{"Information":"Some data here \\"stuff\\" some more.","AnswerToEverything":42,"Other":71,"Name":"Joe Doe"}"""
assert !json1.contains("\\")
assert json2.contains("\\")
assert json2.replace("""\\\"""", "replacement").contains("replacement")
ataylor
Didn't work, I used your code to create a simple test, the code is in the original question (formatting doesn't work on comments).
Cleber Goncalves
Thanks for the input, I actually have no control of the contents of the input JSON, the string I'm getting is like your 'json1' example, I'm trying to remove the \" so the JSON parser works. To escape the slashes ( \\" ) I would have to edit the input manually, which I can't, or figure out a way to detect the \" in a regex, so I could replace it by \\" or just remove it.
Cleber Goncalves