如何绕过CF8编码不可打印字符的SerializeJSON?

时间:2009-07-24 10:54:33

标签: json coldfusion

SerializeJSON使用不可打印的字符(即ASCII 21)创建JSON

这是无效的JSON。我怎么能绕过这个。

正则表达式会删除不可打印的字符吗?

什么正则表达式会删除不可打印的字符?

1 个答案:

答案 0 :(得分:4)

嗯,这个简单的解决方案是为cffeed创建的,但你的问题非常相似。

首先,我尝试使用Java库StringEscapeUtils(Commons Lang API),但它没有正确地转义我的内容。虽然推荐用于XML。

所以,这个cfc方法适合我。也许会帮助你。

<cffunction name="cleanXmlString" access="public" returntype="any" output="false" hint="Replace non-valid XML characters">
    <cfargument name="dirty" type="string" required="true" hint="Input string">
    <cfset var cleaned = "" />
    <cfset var patterns = "" />
    <cfset var replaces = "" />

    <cfset patterns = chr(8216) & "," & chr(8217) & "," & chr(8220) & "," & chr(8221) & "," & chr(8212) & "," & chr(8213) & "," & chr(8230) />
    <cfset patterns = patterns & "," & chr(1) & "," & chr(2) & "," & chr(3) & "," & chr(4) & "," & chr(5) & "," & chr(6) & "," & chr(7) & "," & chr(8) />
    <cfset patterns = patterns & "," & chr(14) & "," & chr(15) & "," & chr(16) & "," & chr(17) & "," & chr(18) & "," & chr(19) />
    <cfset patterns = patterns & "," & chr(20) & "," & chr(21) & "," & chr(22) & "," & chr(23) & "," & chr(24) & "," & chr(25) />
    <cfset patterns = patterns & "," & chr(26) & "," & chr(27) & "," & chr(28) & "," & chr(29) & "," & chr(30) & "," & chr(31) />

    <cfset replaces = replaces & "',',"","",--,--,..." />
    <cfset replaces = replaces & ",-, , , , , , , " />
    <cfset replaces = replaces & ", , , , , , " />
    <cfset replaces = replaces & ", , , , , , " />
    <cfset replaces = replaces & ", , , , , , " />

    <cfset cleaned = ReplaceList(arguments.dirty, patterns, replaces) />

    <cfreturn cleaned />

</cffunction>