Reputation: 1345
I have JSON data like the following
{
"category" : [
{
"name" : "digital stickers",
"products" : [
{
"name" : "round digital stickers",
"urlPublic" : "index.cfm/digital-stickers/round-stickers",
"urlPortal" : "tab=round digital stickers"
},
{
"name" : "square digital stickers",
"urlPublic" : "index.cfm/digital-stickers/square-stickers",
"urlPortal" : "tab=square digital stickers"
}
]
},
{
"name" : "Litho stickers",
"products" : [
{
"name" : "round litho stickers",
"urlPublic" : "index.cfm/litho-stickers/round-stickers",
"urlPortal" : "tab=round litho stickers"
},
{
"name" : "square litho stickers",
"urlPublic" : "index.cfm/litho-stickers/square-stickers",
"urlPortal" : "tab=square litho stickers"
}
]
}
]
}
I have used DeserializeJSON(theData)
as below
<cfset cfData=DeserializeJSON(theData)>
I have then set a data array to store the category values
<cfset dataArray = cfData.category>
and have spat them out in a loop
<cfloop array="#dataArray#" index="elem">
<!--- print out value for demo purposes --->
<cfoutput>
<h3>#elem.name#</h3>
</cfoutput>
</cfloop>
This is all working great and I see the 2 category headings - 'digital stickers' and 'litho stickers'.
What I want to do now is display the products in a list under each relevant category. So under 'digital stickers' to have 'round digital stickers' and 'square digital stickers', then under Litho stickers to have 'round litho stickers' and 'square litho stickers' etc.
I tried to create a new array as below
<cfset productArray = cfData.products>
but I got the error message 'Element PRODUCTS is undefined in CFDATA'
Then my plan was to set this loop inside the current loop to loop through the relevant products. I think I may need a separate array for each category to loop through the products in that specific category.
Any help would be greatly appreciated - thanks in advance!
Upvotes: 3
Views: 573
Reputation: 2525
You are getting error because products are not under cfData
. The products array is under cfdata.category[i].products
. To achieve the desired result, you can do something like below:
<cfoutput>
<h3>#elem.name#</h3>
<cfloop array="#elem.products#" index="innerelem">
#innerelem.name#<br>
</cfloop>
</cfoutput>
Update:
Once you deserialize the JSON, it is just a normal structure. Your cfdata.category (dataArray)
is a array of structures
with name and products keys. The products is another array of structures
.
When you loop through dataArray, in the elem variable you get a structure with name and products keys. Then you need to loop through products to get names within products which is what i am doing in the above code.
To understand the code, use cfdump at every stage.
Upvotes: 3