问题
I am looping over an array of structures and trying to assign and store all key values. If I wrap inner loop in <cfoutput>, I am getting an error: "Complex object types cannot be converted to simple values". If I leave it out, then it does not work. What am I missing?
<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>
Here is the output:
#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]#
回答1:
trying to assign and store all key values
While you could technically output all of the keys dynamically, if the ultimate goal is to manipulate and/or store the values, then dynamic looping probably isn't what you want anyway. To extract specific values, just reference the keys names explicitly - using dot-notation. For example:
<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>
However, to answer your question, the error message just means that cfoutput can only handle simple values. Since some of the values you're trying to display are actually structures (i.e. complex objects), like label and states, the cfoutput chokes when it tries to output them.
来源:https://stackoverflow.com/questions/57066437/how-to-loop-over-array-of-structures-and-display-all-key-values