Escaping '$' character in Description field text inside JSON REST API POST

Kevin Watson March 28, 2018

My replace function below seems to work for other special characters but cannot get it to work for $ symbol - any advice would be most appreciated as I've tried all variations I can think of and have read so far...

def jsonEscape = {

it.replace("\\","\\\\")

.replaceAll("\r","\\\\r")

.replaceAll("\n","\\\\n")

.replaceAll("\t","\\\\t")

.replaceAll("\"","\\\\\"")

//.replace("\$","\\\\\$") 

}

 

1 answer

1 accepted

1 vote
Answer accepted
Kevin Watson April 1, 2018

Finally figured this out, so am posting answer in case it helps someone else...

the solution is:

.replace("\$","\\\$")

note 3 backslashes in replace, presumably 2 backslashes to escape then \$ to escape in JSON.

Anyways, it works nicely...

Tommie Marais April 14, 2021

Good day,

I am new to API's and do not know where to place this portion of the code.

Will you please assist

Kevin Watson April 15, 2021

Hi Tommie,

its difficult for me to answer properly without knowing what you're trying to achieve. In my case the code was in a groovy file referenced inside a Jira Workflow process step. The first part of the code - see below, is called a Closure in groovy and can be called multiple times in the remainder of the code. I usually place Closure code at the beginning, just after the code to import library files.

//** Removes CR/LF & Tab characters that break the JSON Parser and replaces them with escaped characters **//
def jsonEscape = {
    it.replace("\\","\\\\") // Java Regex needs an escape before backslash to pick up, hence look for \\ but to escape in JSON needs to escape that so \\\\
    .replaceAll("\r","\\\\r") // carriage return
    .replaceAll("\n","\\\\n") // new line
    .replaceAll("\t","\\\\t") // tab
    .replaceAll("\"","\\\\\"") // double quote
    .replace("\$","\\\$") // adds backslash prefix to $ symbol
}

Below are two examples which call the above Closure:

def cleanSummary = jsonEscape(issue.getSummary())
def cleanDescription = jsonEscape(issue.getDescription())

I hope this helps...

Like Gordon McDonald likes this

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events