ColdFusion function to convert a query to JSON

UPDATE 12/29/2012: Please check the “How to convert a SQL query to a JS object” post for a much better way to handle SQL queries that need to be converted to Javascript objects.

Just a quick one. I wrote this generic function today to convert any query to a valid JSON string with lowercase element names.

<cffunction name="queryToJSON" returntype="string" access="public" output="yes">
  <cfargument name="q" type="query" required="yes" />
  <cfset var o=ArrayNew(1)>
  <cfset var i=0>
  <cfset var r=0>
  <cfloop query="Arguments.q">
    <cfset r=Currentrow>
    <cfloop index="i" list="#LCase(Arguments.q.columnList)#">
      <cfset o[r][i]=Evaluate(i)>
    </cfloop>    
  </cfloop>
  <cfreturn SerializeJSON(o)>
</cffunction>

Just call this function with:

<cfset myJSON=queryToJSON(yourQueryName)>
share