How to loop over array of structures and display all key values

时间秒杀一切 提交于 2019-12-12 11:51:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!