Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON value with apostrophe [duplicate]

I have an element with a rel attribute that contains a JSON string, something like:

rel='{"id":"#id#","name":"#name#"}'

Then, in my javascript code, I use $.parseJSON to parse this data. This works correctly - besides for cases where name contains an apostrophe. I've tried using jsStringFormat, a coldfusion replace that replaces all single quotes with escaped single quotes, etc, but I can't seem to hit on a correct solution. I know this is probably simple, but how do I get the code to correctly pass values with apostropes/single quotes using json?

This code works, but eliminates the apostrophes which I'd like to preserve:

rel='{"id":"#id#","name":"#replace(name,"'","","all")#"}'

This does not work:

rel='{"id":"#id#","name":"#replace(name,"'","\'","all")#"}'

Nor does:

rel='{"id":"#id#","name":"#replace(name,"'","\\\'","all")#"}'

Or:

rel='{"id":"#id#","name":"#replace(name,"'",""","all")#"}'

Or:

rel='{"id":"#id#","name":"#jsStringFormat(name)#"}'
like image 344
froadie Avatar asked Aug 27 '12 19:08

froadie


2 Answers

After lots of playing around, I finally got this to work :)

rel='{"id":"#id#","name":"#replace(name,"'","&##39;","all")#"}'
like image 96
froadie Avatar answered Oct 28 '22 10:10

froadie


The issue you're having is because you are dealing with a string in two contexts. You need to make sure that the string is safe in both.

JSON string:

The easiest way to make the code JSON safe is to use SerializeJSON function to convert a ColdFusion object into valid JSON.

Thus your code could become:

rel='#SerializeJSON({"id"=Variables.id,"name"=Variables.name})#'

HTML attribute string:

The next context that you need to deal with is that you want the string to be a valid html attribute value.

In ColdFusion 10 you would handle this with the EncodeForHTMLAttribute function.

rel='#EncodeForHTMLAttribute(SerializeJSON({"id"=Variables.id,"name"=Variables.name}))#'

If you're using something prior to CF10 then using the ESAPI encoder is your best bet. (This was included with patches on some versions of ColdFusion)

rel='#CreateObject("java", "org.owasp.esapi.ESAPI").encoder().encodeForHTMLAttribute(SerializeJSON({"id"=Variables.id,"name"=Variables.name}))#'

I personally use a helper CFC to deal with ESAPI encoder in CF9, so CreateObject is only called once and reused for all uses of its methods.

like image 34
nosilleg Avatar answered Oct 28 '22 09:10

nosilleg