ColdFusion 2018 processing an array of structs

669 views Asked by At

I am having issues processing the inner array (variants). Getting Object of type class java.lang.String cannot be used as an array

enter image description here

<cfset jsonData = deserializeJSON(httpResp.fileContent) />
    
<cfset products = jsonData.products>

<cfoutput>

    <cfloop array="#products#" index="x">   
        #x.id# - #x.handle# <br>
                    
        <cfset variants = "variants">
        
        <cfloop array="variants" index= "i">
            #i.barcode#
        </cfloop>
        
    </cfloop>    

</cfoutput>
2

There are 2 answers

1
epipko On BEST ANSWER

With help of RRK (not sure how to give him credit for it), I was able to make it work:

<cfset jsonData = deserializeJSON(httpResp.fileContent) />     
<cfset products = jsonData.products>
<cfoutput>  
    <cfloop array="#products#" index="x">   
        #x.id# - #x.handle# <br>
                    
        <cfset variants = "#x.variants#">           
        <cfloop array="#variants#" index= "i">
            <cfif IsDefined("i.barcode") and i.barcode is not "">
                #i.barcode# <br>
            </cfif>
        </cfloop>
        
    </cfloop>        
</cfoutput>
1
James A Mohler On

Try using cfscript

<cfscript>
jsonData = deserializeJSON(httpResp.fileContent);
    
products = jsonData.products;


for (product in products) {
   writeoutput("#product.id# - #product.handle# <br>");

   for (variant in product.variants) {
     writeoutput(variant.barcode);
   }  
}
</cfscript>