ColdFusion & AJAX: Converting ColdFusion Objects to Javascript Objects

<cffunction name="QueryToArray" access="public" returntype="string" output="false"
	hint="Converts a query into Javascript code for an array of structures. Will return strings in the form of 'new Array(new Object(), new Object()....);'">

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

	<cfscript>

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

		// Convert the column list to an array for faster parsing.
		LOCAL.ColumnList = ListToArray( ARGUMENTS.Data.ColumnList );

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

		// Start the array. This array will be an array of objects.
		LOCAL.ResponseBuffer.Append( "new Array(" );

		// Loop over the query and create an object for each for.
		for (LOCAL.Row = 1 ; LOCAL.Row LTE ARGUMENTS.Data.RecordCount ; LOCAL.Row = (LOCAL.Row + 1)){

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

			// Loop over the columns to create the object values.
			for (LOCAL.Column = 1 ; LOCAL.Column LTE ArrayLen( LOCAL.ColumnList ) ; LOCAL.Column = (LOCAL.Column + 1)){

				// Get the key.
				LOCAL.Key = LOCAL.ColumnList[ LOCAL.Column ];

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

				// 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.Column LT ListLen( ARGUMENTS.Data.ColumnList )){
					LOCAL.ResponseBuffer.Append( "," );
				}

			}

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

			// Check to see if we will have more objects to add.
			if (LOCAL.Row LT ARGUMENTS.Data.RecordCount){
				LOCAL.ResponseBuffer.Append( "," );
			}

		}

		// End the array.
		LOCAL.ResponseBuffer.Append( ")" );

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

	</cfscript>
</cffunction>

For Cut-and-Paste