Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent SerializeJSON from changing Yes/No/True/False strings to boolean?

I have a data struct being stored in JSON format, converted using the serializeJSON function. The problem I am running into is that strings that can be boolean in CF such as Yes,No,True,and False are converted into JSON as boolean values. Below is example code. Any ideas on how to prevent this?

Code:

<cfset test = {str='Yes'}>
<cfset json = serializeJSON(test)>
<cfset fromJSON = deserializeJSON(json)>

<cfoutput>
    #test.str#<br>
    #json#<br>
    #fromJSON.str#
</cfoutput>

Result:

Yes
{"STR":true}
YES
like image 962
Dan Roberts Avatar asked Dec 08 '09 15:12

Dan Roberts


3 Answers

Adding an extra space in the string to prevent it from being converted to boolean, then trim at a later stage.

like image 183
Dan Roberts Avatar answered Oct 23 '22 21:10

Dan Roberts


I believe that your or any similar "string forcing" workaround is the only possible way to prevent such behavior in Adobe CF for now.

BTW, Railo works as expected with your example. Here is the output:

Yes
{"STR":"Yes"}
Yes 

It is also works same way for the numbers with trailing zeros.

like image 25
Sergey Galashyn Avatar answered Oct 23 '22 21:10

Sergey Galashyn


Here's good news for those running CF2018 and 2021. The code in the original post (from cf9 in 2009) does indeed now return was Dan Roberts was expecting:

Yes
{"STR":"Yes"}
Yes

That's without any need of specifying any non-default settings in the app, application.cfc, admin, or jvm args.

Curiously, CF2016 (even the final update, 17) does still return:

Yes
{"STR":true}
YES

But as was noted by kuhl above, you CAN get the desired behavior in CF2016 with the setmetadata function (and it still works fine in 2018 and 2021, of course). Here it is, as script:

<cfscript>
   // changing the default serialization by specifying the datatype of the "str" struct key to be  string
   metadata = {str: {type:"string"}};
   test.setMetadata(metadata);
   writeoutput(SerializeJSON(test));
</cfscript>

which produces:

{"STR":"Yes"}
like image 40
charlie arehart Avatar answered Oct 23 '22 20:10

charlie arehart