Prevent ColdFusion from converting string to number using SerializeJSON

I know this issue is old, but as a new CF developer, I came across this same issue, and while I used the 'string Hack' above successfully, finally I found a more suitable resolution from the Cold Fusion docs for serializeJSON.

'Adobe ColdFusion (2016 release) Update 2 enables you to specify the datatype information for keys in a struct. This is known as metadata.'

<cfscript>
   example = structnew();
   example.firstname = "Yes";
   example.lastname = "Man";
   writeoutput("<b>After serialization</b>:");
   // change the JSON key firstname to fname 
   metadata = {firstname: {type:"string",name:"fname"}};
   example.setMetadata(metadata);
   writeoutput(SerializeJSON(example));
</cfscript>

While the example shows modifying the metadata for the string 'Yes', to stay a string, and not be converted to a boolean, it works just as well for turning numbers into strings for JSON serialization.


Here's a solution - albeit a very hacky, inelegant solution...

Your setup:

var test = {
  name = "1234.100"
};

Adding some obvious string to the front forces the value to become a string when it is converted to JSON. Then we get rid of this ugly string.

var thisIsSuchAHorribleHack = "(!@$!@$)";
test.name = thisIsSuchAHorribleHack & test.name;
var serializedTest = SerializeJSON(test);
serializedTest = Replace(serializedTest, thisIsSuchAHorribleHack, "", "ALL");
writeOutput(serializedTest);