Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent ColdFusion from converting string to number using SerializeJSON

I have ColdFusion 9.0.1 with the latest hotfix (4). I need ColdFusion to return all JSON data with quotes around them (as strings). I have the following problem:

<cfset test = StructNew()>
<cfset test.name = "1234.100">
<cfoutput>#SerializeJSON(test)#</cfoutput>

The text that is outputted is:

{"name":1234.100}

Every javascript JSON parser converts that to 1234.1 and is not keeping the trailing 0's. I either need ColdFusion to output as string or a javascript parser to keep the trailing 0's. Any ideas?

This is a simplified example. I am grabbing this data from a database.

like image 361
Scott Chantry Avatar asked Nov 07 '13 00:11

Scott Chantry


1 Answers

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.

like image 198
Fred Lintz Avatar answered Sep 18 '22 23:09

Fred Lintz