Skip to content

Instantly share code, notes, and snippets.

@pud
Last active December 15, 2015 09:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save pud/5235862 to your computer and use it in GitHub Desktop.
Convert a query result to JSON in ColdFusion
<cffunction name="QueryToStructLowerCase" access="public" returntype="any" output="false"
hint="Converts an entire query or the given record to a struct. This might return a structure (single record) or an array of structures.">
<cfargument name="Query" type="query" required="true" />
<cfargument name="Row" type="numeric" required="false" default="0" />
<!--- Thanks to: http://www.bennadel.com/index.cfm?event=blog.view&id=149 --->
<cfscript>
var local.local = StructNew();
if (ARGUMENTS.Row){
local.local.FromIndex = ARGUMENTS.Row;
local.local.ToIndex = ARGUMENTS.Row;
} else {
local.local.FromIndex = 1;
local.local.ToIndex = ARGUMENTS.Query.RecordCount;
}
local.local.Columns = ListToArray( lcase(ARGUMENTS.Query.ColumnList) );
local.local.ColumnCount = ArrayLen( local.local.Columns );
local.local.DataArray = ArrayNew( 1 );
for (local.local.RowIndex = local.local.FromIndex ; local.local.RowIndex LTE local.local.ToIndex ; local.local.RowIndex = (local.local.RowIndex + 1)){
ArrayAppend( local.local.DataArray, StructNew() );
local.local.DataArrayIndex = ArrayLen( local.local.DataArray );
for (local.local.ColumnIndex = 1 ; local.local.ColumnIndex LTE local.local.ColumnCount ; local.local.ColumnIndex = (local.local.ColumnIndex + 1)){
local.local.ColumnName = local.local.Columns[ local.local.ColumnIndex ];
local.local.DataArray[ local.local.DataArrayIndex ][ local.local.ColumnName ] = ARGUMENTS.Query[ local.local.ColumnName ][ local.local.RowIndex ];
}
}
if (ARGUMENTS.Row){
return( local.local.DataArray[ 1 ] );
} else {
return( local.local.DataArray );
}
</cfscript>
</cffunction>
<cffunction name="queryToJson" output="no">
<cfargument name="q" required="yes" type="query">
<cfreturn serializejson(QueryToStructLowerCase(q))>
</cffunction>
<!---
USAGE:
<cfset foo = queryToJson(myQuery)>
--->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment