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
Adding an extra space in the string to prevent it from being converted to boolean, then trim at a later stage.
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.
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With