Marthinus Strydom
Marthinus Strydom

Reputation: 23

Looping over a nested array

I am struggling to get this to work. I need to loop over the structure but I am getting an error: "Object of type class coldfusion.runtime.Struct cannot be used as an array"

Part of the same JSON

This is what I tried.

<cfoutput>
<h4>Ingredients</h4>
<cfloop index="i" from="1" to="#arrayLen(contents['recipeIngredient'])#">
    #contents['recipeIngredient'][i]# <br>
</cfloop> 
This works...

<h4>Instructions</h4>
<cfloop index="i" from="1" to="#arrayLen(contents['recipeInstructions'])#">
    #contents['recipeInstructions'][i]['@type']# <br>
    #contents['recipeInstructions'][i]['name']# <br>
    #contents['recipeInstructions'][i]['text']# <br>
    #contents['recipeInstructions'][i]['url']# <br>
    #contents['recipeInstructions'][i]['image']# <br>
    <br>
</cfloop>
</cfoutput>
This doesnt work...

I am getting an error for "Instructions": "Object of type class coldfusion.runtime.Struct cannot be used as an array".

Can anyone please assist? I have been around in circles for 2 days.

Upvotes: 0

Views: 113

Answers (1)

accidentalcaveman
accidentalcaveman

Reputation: 127

The code you are using has references to property names that do not appear to exist from the image you provided. I don't see name, url, or image anywhere in the provided structs.

If you are trying to use the same cfm for several different data formats, then you need to at least make sure that the struct keys exist. Or even better, just use the keys that do exists. You could potentially do something like this:

<cfloop index="i" from="1" to="#arrayLen(contents['recipeInstructions'])#">
  <cfset instruction = contents.recipeInstructions[i]/>
  <cfloop item="key" collection="#instruction#">
    #instruction[key]#<br>
  </cfloop>
  <br>
</cfloop>

Upvotes: 1

Related Questions