CFLib.org – Common Function Library Project

queryStringToStruct([qs])

Last updated April 11, 2006

author

Malessa Brisbane

Version: 1 | Requires: CF5 | Library: UtilityLib

Description:
Converts a URL query string to a structure. Repeated keys have the values appended as a list. Also removes and URL encoding. Based on code from QueryStringDeleteVar. This UDF is not typically needed since ColdFusion automatically converts the query string into the URL structure, but since you can pass in a custom query string, it could be useful for parsing those strings instead.

Return Values:
Returns a struct.

Example:

<cfdump var="#udf_QueryStringToStruct()#">
<cfdump var="#udf_QueryStringToStruct('test=123&test=456&x=apple&y=oranges')#">

Parameters:

Name Description Required
qs Query string to parse. Defaults to cgi.query_string. No

Full UDF Source:

/**
 * Converts a URL query string to a structure.
 * 
 * @param qs      Query string to parse. Defaults to cgi.query_string. (Optional)
 * @return Returns a struct. 
 * @author Malessa Brisbane (cflib@brisnicki.com) 
 * @version 1, April 11, 2006 
 */
function queryStringToStruct() {
    //var to hold the final structure
    var struct = StructNew();
    //vars for use in the loop, so we don't have to evaluate lists and arrays more than once
    var i = 1;
    var pairi = "";
    var keyi = "";
    var valuei = "";
    var qsarray = "";
    var qs = CGI.QUERY_STRING; // default querystring value
    
    //if there is a second argument, use that as the query string
    if (arrayLen(arguments) GT 0) qs = arguments[1];

    //put the query string into an array for easier looping
    qsarray = listToArray(qs, "&");
    //now, loop over the array and build the struct
    for (i = 1; i lte arrayLen(qsarray); i = i + 1){
        pairi = qsarray[i]; // current pair
        keyi = listFirst(pairi,"="); // current key
        valuei = urlDecode(listLast(pairi,"="));// current value
        // check if key already added to struct
        if (structKeyExists(struct,keyi)) struct[keyi] = listAppend(struct[keyi],valuei); // add value to list
        else structInsert(struct,keyi,valuei); // add new key/value pair
    }
    // return the struct
    return struct;
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson