Skip to main content
Inspiring
May 13, 2021
Answered

json iif() value is returning string instead of boolean (ACF 2021)

  • May 13, 2021
  • 3 replies
  • 652 views

Hi,

 

The iif() is returning boolean when json serialized it's returning string instead of boolean. Thanks. 

Tested on Adobe Coldfusion 2021.

 

Here is the code:

<cfscript>
local.test = true;
local.return = {
"hasFeed" = iif(local.test,true,false)
};
writeoutput(serializejson(local.return));
</cfscript>
 
    This topic has been closed for replies.
    Correct answer EddieLotter

    Using cffiddle.org, the result seems to have changed in CF 2018.

    As a work around you can change the iif() to the elvis operator:

    "hasFeed" = local.test ? true : false

    3 replies

    BKBK
    Community Expert
    Community Expert
    May 19, 2021

    Hi @joseph.yan , ColdFusion is weakly typed, so there are no guarantees. Under the covers, every simple-value is basically a string. Illustration:

    <cfscript>
    writeoutput('"false"==false: ' &  ("false"==false));
    writeoutput("<br>");
    writeoutput('"true"==true: ' &  ("true"==true));
    writeoutput("<br>");
    writeoutput('"true"==false: ' &  ("true"==false));
    writeoutput("<br>");
    writeoutput('"false"==0: ' &  ("false"==0));
    writeoutput("<br>");
    writeoutput('"true"==1: ' &  ("true"==1));
    </cfscript>

     

    In any case, there is a remedy for the datatypes in a struct: structSetMetadata. If you apply it, your output will be:

     

    {"hasFeed":true}

     

    <cfscript>
    local.test = true;
    
    // specify datatype for key 'hasFeed'
    metadata = {hasFeed: {type:"boolean"}};
    
    local.return = {
    "hasFeed" = iif(local.test,true,false)
    };
    
    structSetMetaData(local.return,metadata);
    
    writeoutput(serializejson(local.return));
    </cfscript>

     

     

    EddieLotter
    EddieLotterCorrect answer
    Inspiring
    May 13, 2021

    Using cffiddle.org, the result seems to have changed in CF 2018.

    As a work around you can change the iif() to the elvis operator:

    "hasFeed" = local.test ? true : false
    Inspiring
    May 13, 2021

    Yeah, the elvis operator works. I think the elvis absolutely much better than iif. Thank you for your help.

    George____
    Inspiring
    May 13, 2021

    I'd say this is consistent with the documentation.

    It states "Depending on whether the expression is yes or no, dynamically evaluates one of two string expressions and returns the result."

    The 2nd and 3rd parameters are string expressions, so Coldfusion is being helpful by treating true as "true" and returning that.