Converting structkeys to lowercase
As you most probably know when you create a structure and don't quote the keys they are automatically converted to uppercase.
<cfset myStruct = structNew()>
<cfset mystruct.one=1>
<cfset mystruct.two=2>
<cfset mystruct.three=3>
When you dump it out you get:

and when you serialize it to json all the keys are also uppercase. This can be problematic since JS is case sensitive. You could create your structure with lowercase keys then serializeJSON() will maintain the case of your structure, but if you don't have control of the structure itself you need to do something to to convert only the structure keys to lowercase.
As a quick and dirty way of doing this I build a recursive function to do just that. Firstly I ran the structure through SerializeJSON() just in case the structure contained other datatypes that also need to be serialized, I think deserialized the string back into a structure. Make sure you use strict mapping so that the function doesn't try to convert your query back into a query. Then call the recursive function to go through and change all the keys to lowercase.
Here is the function:
<cffunction name="convertStructToLower" access="public" returntype="struct">
<cfargument name="st" required="true" type="struct">
<cfset var aKeys = structKeyArray(st)>
<cfset var stN = structNew()>
<cfset var i= 0>
<cfset var ai= 0>
<cfloop array="#aKeys#" index="i">
<cfif isStruct(st[i])>
<cfset stN['#lCase(i)#'] = convertStructToLower(st[i])>
<cfelseif isArray(st[i])>
<cfloop from=1 to="#arraylen(st[i])#" index="ai">
<cfif isStruct(st[i][ai])>
<cfset st[i][ai] = convertStructToLower(st[i][ai])>
<cfelse>
<cfset st[i][ai] = st[i][ai]>
</cfif>
</cfloop>
<cfset stN['#lcase(i)#'] = st[i]>
<cfelse>
<cfset stN['#lcase(i)#'] = st[i]>
</cfif>
</cfloop>
<cfreturn stn>
</cffunction>
As you can see it also handles the case where you have an array of structures inside a structure.
I've tested it with nested structures that contain arrays of structures and it seems to work just fine. Perhaps you will find it useful for any Ajax stuff you are doing.
Happy Coding...





Subscribe via RSS
Follow me on Twitter