JSON value with apostrophe [duplicate]

删除回忆录丶 提交于 2019-12-10 14:19:02

问题


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)#"}'

回答1:


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

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



回答2:


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.




回答3:


In JavaScript, escape single quotes in strings with \.

In HTML, you should really use double quotes for attributes though, and escape the double quotes, for example:

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


来源:https://stackoverflow.com/questions/12148468/json-value-with-apostrophe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!