1

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>
James A Mohler
  • 11,060
  • 15
  • 46
  • 72
epipko
  • 473
  • 5
  • 18
  • 3
    You need to use `` or use it directly in the loop like ``. – rrk Sep 14 '20 at 19:20
  • Thanks, it works, but now I am getting "Element BARCODE is undefined in I. " – epipko Sep 14 '20 at 19:31
  • The reason you are getting "`Object of type class java.lang.String cannot be used as an array`" is because you are setting `` and overwriting the `variants` element from inside the `products` struct on each loop. Remove that `cfset` and change your loop array to `#x.variants#` and it should do what you need. – Shawn Sep 15 '20 at 18:14
  • And then for `#i.barcode#`, you can give it `#i.barcode?:""#` to default it to an empty string if it isn't defined. – Shawn Sep 15 '20 at 18:16

2 Answers2

0

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>
James A Mohler
  • 11,060
  • 15
  • 46
  • 72
0

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>
epipko
  • 473
  • 5
  • 18
  • See my comment above about using Elvis Operator instead of `isDefined`. Or use `structKeyExists` instead of `isDefined`. – Shawn Sep 15 '20 at 18:18