coldfusion - ColdFusion 循环遍历具有空/未定义字段的数组
问题描述
我正在从我们的供应商之一的 API 下载数据。数据是一个数组,但有些字段是空的,并以undefined
. 我可以通过循环获取大部分信息,但是当我添加“注释”字段时,它会失败并出现以下错误:
“元素注释在作为表达式的一部分引用的 CFML 结构中未定义。包含或处理的文件的特定顺序是:
C:\websites\Fire\Reports\xml_parse\Crewsense_payroll_loop.cfm,第 21 行
当我查看转储时,我看到该字段显示为“未定义”。我已经没有想法了。任何帮助将不胜感激。我已经包含了整个代码和一个指向显示数组的转储的链接。
<cfhttp url="https://api.crewsense.com/v1/payroll? access_token=as;lkdfj;alskdfj;laksdfj&token_type=bearer&start=2019-01-05%2019:00:00&end=2019-01-06%2007:59:00" method="GET" resolveurl="YES" result="result">
</cfhttp>
<cfoutput>
<cfset ApiData = deserializeJSON(result.filecontent)>
<cfset API_ArrayLength = arraylen(ApiData)>
<cfloop index="i" from="1" to=#API_ArrayLength#>
#i# #ApiData[i]["name"]#
#ApiData[i]["employee_id"]#
#ApiData[i]["start"]#
#ApiData[i]["end"]#
#ApiData[i]["total_hours"]#
#ApiData[i]["work_type"]#
#ApiData[i]["work_code"]#
#ApiData[i]["user_id"]#
#ApiData[i]["notes"]# <---Fails here when added--->
<cfset i = i+1>
<br>
</cfloop>
<cfdump var="#ApiData#">
</cfoutput>
解决方案
在处理具有可选元素的数据结构时,您需要在尝试访问它们之前检查它们的存在。否则你会得到那个错误。作为示例,我在您的代码中添加了一个使用structKeyExists()if
函数的条件片段。
<cfhttp url="https://api.crewsense.com/v1/payroll? access_token=as;lkdfj;alskdfj;laksdfj&token_type=bearer&start=2019-01-05%2019:00:00&end=2019-01-06%2007:59:00" method="GET" resolveurl="YES" result="result">
</cfhttp>
<cfoutput>
<cfset ApiData = deserializeJSON(result.filecontent)>
<cfset API_ArrayLength = arraylen(ApiData)>
<cfloop index="i" from="1" to=#API_ArrayLength#>
#i# #ApiData[i]["name"]#
#ApiData[i]["employee_id"]#
#ApiData[i]["start"]#
#ApiData[i]["end"]#
#ApiData[i]["total_hours"]#
#ApiData[i]["work_type"]#
#ApiData[i]["work_code"]#
#ApiData[i]["user_id"]#
<cfif structKeyExists(ApiData[i],"notes")>
#ApiData[i]["notes"]# <!--- Show 'notes' if it exists --->
<cfelse>
'notes' is not available <!--- Do something here (or not) --->
</cfif>
<cfset i = i+1>
<br>
</cfloop>
<cfdump var="#ApiData#">
</cfoutput>
推荐阅读
- google-cloud-sql - Google Cloud SQL 上的 PostgREST:unix 套接字 URI 格式?
- flutter - 转换为类型类 dart http 响应体
- java - 依赖关系引入了一个传递库,该库使用 TIFF 文件破坏 ImageIO.read
- java - 如何从处理器内的 Apache Camel 中的路由获取响应并在处理器内调用该路由?
- groovy - Spock-在被测类的私有方法调用中捕获方法参数
- scala - Scala Style:所有分支的模式匹配都是带有模式保护的通配符
- node.js - 使用特定选项或环境变量在 AWS lambda 中启动 NodeJS 运行时
- apache-spark - Apache Spark 驱动程序日志未指定阶段取消的原因
- docker - docker中的Gulp watch在docker中花费太长时间
- .net-core - 实体框架核心 3.1 中的 Pluralizer 模型名称