Convert a query result to JSON in ColdFusion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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