In ColdFusion if you use the SerializeJSON function on an object, the values for each key get converted into JSON values.
This means that zip codes like “02115″ (regardless if they are strings or integers) are converted to 2115.0 and large numbers like cellphone numbers—3132123232 are converted to scientific notation (3132123232E9 or something like that, too lazy to get it exactly right).
This blog post: from 2008 that addresses it and provides a solution, but the solution doesn’t work for the larger floating point numbers with the E. I’ve fixed (and simplified) the code below—it’s in cftag form now:
<!---
- SerializeJSON converts string numbers into JSON numbers (e.g. "02115" into 2115.0)
- Use this function to fix those values
- @param json string serialized JSON to search
- @param key string thing with value to replace
- @param value string value to replace with string value instead of JSONified value
- @param replaceAll bool should the function replace all instances of the key:value or just the first one?
--->
<cffunction name = "CleanSerializedJSON" output="no">
<cfargument name = "json" />
<cfargument name = "key" />
<cfargument name = "value" />
<cfargument name = "replaceAll" />
<cfif arguments.replaceAll>
<cfset ret = ReReplaceNoCase(Trim(arguments.json), '"#arguments.key#":[\d\.E]*', '"#arguments.key#":"#arguments.value#"', "ALL") />
<cfelse>
<cfset ret = ReReplaceNoCase(Trim(arguments.json), '"#arguments.key#":[\d\.E]*', '"#arguments.key#":"#arguments.value#"') />
</cfif>
<cfreturn ret />
</cffunction>
The CFFunction should be called as follows:
<cfset variables.cleanJSON = SerializeJSON(variables.output) />
<cfset variables.cleanJSON = CleanSerializedJSON(variables.cleanJSON, 'zip_code', "02115", FALSE) />