如何遍历结构数组并显示所有键值
How to loop over array of structures and display all key values
我正在遍历结构数组并尝试分配和存储所有键值。如果我在 <cfoutput>
中包装内部循环,我会得到一个错误:"Complex object types cannot be converted to simple values"。如果我把它排除在外,那么它就不起作用。我错过了什么?
<cfif isJSON(httpResp.fileContent)>
<cfset jsonData = deserializeJSON(httpResp.fileContent) />
<cfloop from="1" to="#arrayLen(jsonData)#" index="i">
<cfset data = jsonData[i]>
<!---<cfoutput>--->
<cfloop collection="#data#" item="key">
#key#:#data[key]#<br>
</cfloop>
<!---</cfoutput>--->
</cfloop>
<cfdump var="#jsonData#">
<cfelse>
Did not receive a valid Json object
</cfif>
这是输出:
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
trying to assign and store all key values
虽然技术上您可以动态输出所有键,但如果最终目标是操纵 and/or store 值,那么动态循环可能不是什么无论如何你想要。要提取特定值,只需显式引用键名称 - 使用 dot-notation。例如:
<cfloop array="#jsonData#" index="prop">
<cfoutput>
<hr>confirmation = #prop.confirmation#
<br>id = #prop.id#
<br>label.carrier = #prop.label.carrier#
<br>label.tracking = #prop.label.tracking#
<br>order.created_at = #prop.order.created_at#
<br>policy.logistic_code = #prop.policy.logistic_code#
<br>policy.refund_code = #prop.policy.refund_code#
<br>ref.order = #prop.ref.order#
<br>state = #prop.state#
...
</cfoutput>
</cfloop>
但是,为了回答您的问题,错误消息仅表示 cfoutput
只能处理简单值。由于您尝试显示的某些值实际上是结构(即复杂对象),例如 label
和 states
,因此 cfoutput
在尝试输出它们时会阻塞。
我正在遍历结构数组并尝试分配和存储所有键值。如果我在 <cfoutput>
中包装内部循环,我会得到一个错误:"Complex object types cannot be converted to simple values"。如果我把它排除在外,那么它就不起作用。我错过了什么?
<cfif isJSON(httpResp.fileContent)>
<cfset jsonData = deserializeJSON(httpResp.fileContent) />
<cfloop from="1" to="#arrayLen(jsonData)#" index="i">
<cfset data = jsonData[i]>
<!---<cfoutput>--->
<cfloop collection="#data#" item="key">
#key#:#data[key]#<br>
</cfloop>
<!---</cfoutput>--->
</cfloop>
<cfdump var="#jsonData#">
<cfelse>
Did not receive a valid Json object
</cfif>
这是输出:
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
trying to assign and store all key values
虽然技术上您可以动态输出所有键,但如果最终目标是操纵 and/or store 值,那么动态循环可能不是什么无论如何你想要。要提取特定值,只需显式引用键名称 - 使用 dot-notation。例如:
<cfloop array="#jsonData#" index="prop">
<cfoutput>
<hr>confirmation = #prop.confirmation#
<br>id = #prop.id#
<br>label.carrier = #prop.label.carrier#
<br>label.tracking = #prop.label.tracking#
<br>order.created_at = #prop.order.created_at#
<br>policy.logistic_code = #prop.policy.logistic_code#
<br>policy.refund_code = #prop.policy.refund_code#
<br>ref.order = #prop.ref.order#
<br>state = #prop.state#
...
</cfoutput>
</cfloop>
但是,为了回答您的问题,错误消息仅表示 cfoutput
只能处理简单值。由于您尝试显示的某些值实际上是结构(即复杂对象),例如 label
和 states
,因此 cfoutput
在尝试输出它们时会阻塞。