I recently built a CMS that uses a significant amount of Ajax (jQuery). In a particular module, there is a data field that, in some instances, looks like a number but it should behave and be treated as a string. The problem is that it is being treated as a number when ColdFusion serializes the JSON. This is a data field whose rules have morphed over time. Currently, many instances of this data take the following format: 000123. In some cases, a letter had been added to the end, as follows: 000123m. 

When a non-numeric character is anywhere in the string, all is well: ColdFusion serializes the JSON properly. In the cases where an identification number consists of a collection of numeric values only (i.e., 000123), ColdFusion's SerializeJSON function will convert this value (000123) from a string to a number (123.0). I tried a few things to fix it, Googled for answers, but had no luck. 

Ultimately, I had to suck it up and write a basic RegEx to replace the miscast key/value pair in the JSON. I  respect and admire the power of Regular Expressions, however, I have never been able to fully get my head around them (I supposed I get frustrated too quickly trying to make a RegExp work and then throw my hands up and walk away). 

Side note: In my Googling, I stumbled across a really nice tool for testing Regular Expressions in ColdFusion: CFTopper Regular Expression Tester.

Back to it. Because SerializeJSON produces its output in a consistent manner, I created a basic function (housed in a utility CFC) that takes 3 parameters (serialized JSON string, key to replace, value to insert) and replaces the desired key/value pair and returns a string with the properly formatted JSON.

As always, this was written in a rush and could certainly be better or more efficient...however, it worked in all cases that I needed it to! If you think this might help you, have at it.







var ret = "";
var key = Trim(arguments.propName);
var value = Trim(arguments.propVal);
if(arguments.replaceAll){
ret = ReReplaceNoCase(Trim(arguments.serializedJSON),'"#key#":[0-9]*\.[0-9]*','"#key#":"#value#"',"ALL");
}
else{
ret = ReReplaceNoCase(Trim(arguments.serializedJSON),'"#key#":[0-9]*\.[0-9]*','"#key#":"#value#"');
}




For some reason the syntax highlighter is adding in closing tags for the cfarguments and cfreturn. If you happen to copy this function, be sure to clear those out!

I could only find one post on the larger issue of CF's SerializeJSON casting strings to numbers:
ColdFire 1.2.95.100 and a CF to JSON Gotcha

Comments

jackob
Wow this is AWESOME, soooo cool! I didn't even think this was possible! Definately donate!!!!
Thank You
ColdFusion Downloads
jones
Nice blog...
visit also coldfusion example