Sunday, July 25, 2010

Declaring a variable with same name as a column in cfloop

I have a query with a column name json in it, which may or maynot contain a json string. If it does contain json I want to deserialize it, put it into an array loop, and output the results. I want to use the same in a variable as the column coming from the query because it reads good. When I did this I noticed that you can't declare a variable with the same name...even if you prefix the query column.

Here's is my test case. We will break it down in a sec.

<cfset query = queryNew("id,json")/>

<cfset queryAddRow(query)/>
<cfset querySetCell(query,"id","1")/>
<cfset querySetCell(query,"json","")/>

<cfset array = [{id=1,name="Joe"},{id=2,name="Tony"},{id=3,name="Ryan"}]/>

<cfset queryAddRow(query)/>
<cfset querySetCell(query,"id","2")/>
<cfset querySetCell(query,"json",serializeJSON(array))/>

<cfloop query="query">

<cfset json = []/>

<cfif len(query.json) gt 0>
<cfset json = deserializeJSON(query.json)/>
</cfif>

<cfloop from="1" to="#arrayLen(json)#" index="i">
#i.name#
</cfloop>

</cfloop>


The above test case will error out. Because you can't loop the following because ColdFusion thinks that variable "json" is a string, even though I declared it as an array.

<cfloop from="1" to="#arrayLen(json)#" index="i">


First we make a query with a json string in it

<cfset query = queryNew("id,json")/>

<cfset queryAddRow(query)/>
<cfset querySetCell(query,"id","1")/>
<cfset querySetCell(query,"json","")/>

<cfset array = [{id=1,name="Joe"},{id=2,name="Tony"},{id=3,name="Ryan"}]/>

<cfset queryAddRow(query)/>
<cfset querySetCell(query,"id","2")/>
<cfset querySetCell(query,"json",serializeJSON(array))/>


Next we loop the query and check if there is a json string in the query column "JSON". I started an array with the same name as query column json. I did this so if there isn't any json after we deserialize the json it won't error when we try to loop the array.

<cfset json = []/>

<cfif len(json) gt 0>
<cfset json = deserializeJSON(query.json)/>
</cfif>


Lastly I try to loop the array "json" and output the data, but it errors out because it still is looking at the loop variable "json" not the variable I declared "json". Yes, I can solve this problem easily but changing my declared variable from "json" to "array" or something like that, but I wanted to be clear what I was loop...and I just wanted to use the variable name "json".

No comments:

Post a Comment