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;
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson