如何从 cfquery 构建结构?

How to build structure from cfquery?

我有 cffunction 应该 return JSON 结构。我有 50 多个列 return。我不想手动构建我的结构,而是想动态构建它。因此,首先循环查询,然后循环遍历每个 table 列。这是示例:

     <cffunction name="getRecords" access="remote" output="true" returnformat="JSON">
            <cfargument name="userID" type="string" required="true">

            <cfset fnResults = StructNew()>

            <cfquery name="myQuery" datasource="test">
                SELECT 
                   ur_first,
                   ur_last,
                   ur_dob,
                   ur_gender,
                   ur_email,
                   ur_address,
                   ... and the rest of the columns
                FROM Users
                WHERE ur_id = <cfqueryparam value="#trim(arguments.userID)#" cfsqltype="cf_sql_char" maxlength="15">
                ORDER BY ur_createDt
            </cfquery>

            <cfset fnResults.recordcount = myQuery.recordcount>    

            <cfloop query="myQuery">
                <cfset qryRecs = StructNew()>
                <cfloop array="#myQuery.getColumnList()#" index="columnName">
                    <cfset qryRecs.'#columnName#' = URLEncodedFormat('#columnName#')>
                </cfloop>
             </cfloop>

             <cfset fnResults.data = qryRecs>

          <cfreturn fnResults>
     </cffunction>

我在 Ajax 调用后返回此错误:

CFML variable name cannot end with a &quot;.&quot; character.
The variable qryRecs. ends with a &quot;.&quot; character. You must either provide an additional structure key or delete the &quot;.&quot; character.

参考这一行:

443 : <cfset qryRecs.'#columnName#' = URLEncodedFormat('#columnName#')>

我想设置列名来构造 qryRecs,如下所示:

<cfset qryRecs.ur_first = URLEncodedFormat(myQuery.ur_first)>

这样我就不必手动设置 50 多列。它们都应该动态创建。如果有人可以帮助,请告诉我。

我创建了一个 ArrayCollection object 可以将 ColdFusion 查询转换为几种不同的 JSON 格式。看看这是否符合您的需求。

例如,这个查询:

<cfquery name="rs.q" datasource="cfbookclub">
    SELECT DISTINCT
        bookid,
        title,
        genre
    FROM
        books
    WHERE
        title LIKE <cfqueryparam value="%#arguments.term#%" cfsqltype="cf_sql_varchar" />
    ORDER BY
        genre, title
</cfquery>

将转换为 JSON:

{
    "data": [
        {
            "bookid": 8,
            "genre": "Fiction",
            "title": "Apparition Man"
        },
        {
            "bookid": 2,
            "genre": "Non-fiction",
            "title": "Shopping Mart Mania"
        }
    ]
}

我也在进行更新,将元数据添加到 return 消息中:

{
    "success": true,
    "message": "Array Collection created.",
    "meta": {
        "offset": 0,
        "pageSize": 0,
        "totalRecords": 0
    },
    "data": []
};