ColdFusion & AJAX: Converting ColdFusion Objects to Javascript Objects

<cffunction name="StructToObject" access="public" returntype="string" output="false"
	hint="Converts a ColdFusion struct of SIMPLE values into a Javascript object. Will return strings in the form of: new Object({})">

	<!--- Define arguments. --->
	<cfargument name="Data" type="struct" required="true" />

	<cfscript>

		// Define the local scope.
		var LOCAL = StructNew();

		// Create the string buffer for creating the response string.
		LOCAL.ResponseBuffer = CreateObject( "java", "java.lang.StringBuffer" );

		// Start the object.
		LOCAL.ResponseBuffer.Append( "{" );

		// Get the key count.
		LOCAL.KeyCount = StructCount( ARGUMENTS.Data );

		// Get an index for keeping track of the key usage.
		LOCAL.KeyIndex = 1;

		// Loop over the keys to create the object values.
		for (LOCAL.Key in ARGUMENTS.Data){

			// Get the value.
			LOCAL.Value = ARGUMENTS.Data[ LOCAL.Key ];

			// Add the pair. Escape the value so that is doesn't break the string. This requires the
			// use of the "\" before single quotes, double quotes, and backward slashes (which
			// ordinarily would be special characters in Javascript).
			LOCAL.ResponseBuffer.Append( LCase( LOCAL.Key ) & ":""" & REReplace( LOCAL.Value, "(""|\\)", "\\\1", "ALL" ) & """" );

			// Check to see if we need to add the comma.
			if (LOCAL.KeyIndex LT LOCAL.KeyCount){
				LOCAL.ResponseBuffer.Append( "," );
			}

			// Add one to the key index.
			LOCAL.KeyIndex = (LOCAL.KeyIndex + 1);

		}

		// End the object.
		LOCAL.ResponseBuffer.Append( "}" );

		// Return the string.
		return( LOCAL.ResponseBuffer.ToString() );

	</cfscript>
</cffunction>

For Cut-and-Paste