编写逻辑来检查值是否存在

writing a logic to check if value exists

处理代码返回的数据

尝试添加一些逻辑,如果该值存在,则显示它,否则为空

<cfset myStruct = {
    "access_token" : "#st.access_token#",
    "id": "#res.names[1].metadata.source.id#",
    "name" : "#isDefined('res.names') ? res.names[1].displayname : ''#",
    "other" : {
        "email" : "#res.emailAddresses[1].value#"
    }
}>

新开window

它不干净,它在 ID 的第 3 行抛出错误,所以如果它存在我可以写什么样的 isDefined 或 structkeyexists 添加它,否则放一个空值

你可以试试Elvis operator

编辑:除非你真的需要字符串形式的值,否则你不需要使用磅来输出值

编辑 2:已更新示例以使用正确的注释

<cfset myStruct = {
      "access_token" : "#st.access_token#" <!--- If you have numeric token and need it to be a string --->
    , "id"           : res.names[ 1 ].metadata.source.id ?: ""
    , "name"         : res.names[ 1 ].displayname        ?: ""
    , "other"        : {
        "email" : res.emailAddresses[ 1 ].value ?: ""
    }
}>