如何从cfquery构建结构?

时间:2017-06-06 13:28:09

标签: json coldfusion structure coldfusion-9

我有c ffunction应返回JSON结构。我必须返回超过50列。而不是手动构建我的结构,我想动态地构建它。因此,首先循环查询然后循环遍历每个表列。这是一个例子:

     <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多列。它们都应该动态创建。如果有人可以提供帮助,请告诉我。

1 个答案:

答案 0 :(得分:3)

我创建了一个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"
        }
    ]
}

我还在进行一项更新,将元数据添加到返回消息中:

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